Result<T>.from constructor
Result<T>.from (
- T getter(), {
- ExceptionHandler? exceptionHandler,
- String? errorGroup,
A factory constructor to create a Result instance from a function that might throw an exception.
The ExceptionHandler can be provided to handle exceptions and return an ErrorMessage.
The errorGroup
can be used to categorize the type of error.
Implementation
factory Result.from(
T Function() getter, {
ExceptionHandler? exceptionHandler,
String? errorGroup,
}) {
assert(
(exceptionHandler == null && errorGroup == null) ||
(exceptionHandler != null) ^ (errorGroup != null),
'Exception handler and error group are mutually exclusive',
);
try {
return Result.success(getter());
} on Exception catch (e, s) {
return Result.failure(
exceptionHandler?.call(e, s) ??
ErrorMessage.fromException(e, s, source: errorGroup),
);
} catch (e) {
return Result.failure(
ErrorMessage(
message: "Unknown error",
source: errorGroup,
details: e,
),
);
}
}