mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00:00
AK: Add a TRY(expression) macro to simplify the unwrap-or-return pattern
The way we use classes like Kernel::KResultOr<T> and AK::Result<T, E> makes checking for errors (and short-circuiting returns) quite verbose. This patch adds a new TRY(expression) macro that either evaluates to the released result of the expression if successful, or returns the error if not. Before: auto foo_or_error = get_foo(); if (foo_or_error.is_error()) return foo_or_error.release_error(); auto foo = foo_or_error.release_value(); After: auto foo = TRY(get_foo()); The macro uses a GNU C++ extension which is supported by GCC, Clang, Intel C++, and possibly others. It's not *ideal*, but since it makes our codebase considerably nicer, let's try(!) it out. :^) Co-authored-by: Ali Mohammad Pur <mpfard@serenityos.org>
This commit is contained in:
parent
fd44336ef8
commit
b4d8e166d8
Notes:
sideshowbarker
2024-07-18 04:43:56 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/commit/b4d8e166d85
1 changed files with 18 additions and 0 deletions
18
AK/Try.h
Normal file
18
AK/Try.h
Normal file
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// NOTE: This macro works with any result type that has the expected APIs.
|
||||
// It's designed with AK::Result and Kernel::KResult in mind.
|
||||
|
||||
#define TRY(expression) \
|
||||
({ \
|
||||
auto result = (expression); \
|
||||
if (result.is_error()) \
|
||||
return result.release_error(); \
|
||||
result.release_value(); \
|
||||
})
|
Loading…
Reference in a new issue