0 purchases
success
Success
Deal with success or failure in the simplest way.
About #
This simple package presents a way to easily handle a success or failed result, which could be, for example, the result of an API request.
How to #
This package contains only 3 classes, Result and its subtypes - Success and Failure. You can use these classes in your code to handle errors without having to do a try catch whenever possible.
Usage #
enum RequestErrorCode {
noInternet,
sessionExpired,
unexpectedError,
}
Result<Response, RequestErrorCode> getUsername() {
try {
final response = api.getUsername();
} on ApiError catch (err) {
if (err.connectionInterrupted) {
return Result.failure(RequestErrorCode.noInternet);
} else if (err.statusCode == 401) {
return Result.failure(RequestErrorCode.sessionExpired);
} else {
return Result.failure(RequestErrorCode.unexpectedError);
}
} on Exception {
return Result.failure(RequestErrorCode.unexpectedError);
}
}
void main() {
final result = getUsername();
switch (result) {
case Success(value: final username):
print('My username is: "$username".');
break;
case Failure(value: RequestErrorCode.noInternet):
print('Internet connection is not available.');
break;
case Failure(value: RequestErrorCode.sessionExpired):
print('Session has expired.');
break;
case Failure():
print('Unexpected error while getting the username.');
break;
}
}
copied to clipboard
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.