Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Error Handling With Future & Try-Catch Block In Dart

Handle your mistakes! Your application will have blunders. You must deal with them. That is awful. If it will fizzle with an unrecoverable mistake, your application ought to be proactive about it. On the off chance that it should crash, your application should put forth the attempt to do so nimbly. It ought to try and show some strength and not accident too badly — not lose any information, and so forth

Your application ought to likewise be accountable — telling the client what simply occurred, and not simply leaving them featuring on a red screen. Like documentation, mistake taking care of is by all accounts the last thing we developers consider when developing software. That is bad.

In this blog, we will explore the Error Handling With Future & Try-Catch Block In Dart. We’ll stroll through errors you will probably encounter when developing, how to catch and deal with handle errors in Dart, which likewise works in Flutter applications.

Table Of Contents::

What is Error Handling?

What is Error Handling with Future?

How to Using then‘s onError

Why we should using catchError?

How to Using onError?

Using whenComplete

Error Handling with Try-Catch Block

Conclusion



What is Error Handling?:

Error handling alludes to the expectation, detection, and goal of programming, application, and correspondence mistakes. Specific programs, called error overseers, are accessible for certain applications. The best programs of this kind hinder mistakes if conceivable, recuperate from them when they happen without ending the application, or (as a last fails) nimbly end an influenced application and save the error data to a log document.

Uncommon applications known as error controllers are accessible for specific applications to help in mistake taking care of. These applications can expect mistakes, consequently helping in recovering without a genuine end of the application.

There are four principle classifications of errors:

  • > Logical errors
  • > Generated errors
  • > Compile-time errors
  • > Runtime errors

Error-handling care of procedures for advancement errors incorporates thorough editing. Error-handling taking care of strategies for rationale errors or bugs is ordinarily by fastidious application debugging or investigating. Error handling dealing with applications can resolve runtime errors or have their effect limited by receiving sensible countermeasures relying upon the climate. Most hardware applications incorporate error handling dealing with a system that permits them to recover smoothly from surprising errors.

What is Error Handling with Future?:

Future in Dart is depicted as an object that addresses a postponed computation. It’s utilized to address a value or an error that will be accessible later on. Generally, it’s utilized for tasks that need an ideal opportunity to finish, like bringing information over a network or perusing from a record. Those tasks are smarter to be performed asynchronously and normally enclosed by a function that returns Future since you can put asynchronous activities inside a function that returns Future. Dart upholds both Future and async/await designs.

While the function is being executed, it might throw an error. You may have to get the error and figure out what to do if a mistake happens. The following are instances of how to deal with errors in the Future. For this instructional exercise, we will utilize the underneath exception and function.

class MyException implements Exception {}
Future<String> myErrorFunction() async {
return Future.error(new MyException(), StackTrace.current);
}

In the code over, the function throws MyException utilizing Future.error, with the stack follow is additionally passed.

How to Using then‘s onError:

Assuming you are now acquainted with Dart’s Future, you ought to have the then method. It permits you to pass a callback that will be considered when the Future finishes. On the off chance that you take a gander at the signature of then, there is a discretionary boundary onError. The callback passed as the onError argument will be considered when the Future finishes with an error.

The onError callback should acknowledge a couple of parameters. On the off chance that it acknowledges one boundary, it will be called with the error. On the off chance that it acknowledges two parameters, it will be called with the error and the stack trace. The callback needs to return a value or a Future.

Future<R> then<R>(FutureOr<R> onValue(T value), {Function? onError});

The code underneath myErrorFunction throws MyException. The error will be gotten by the onError callback. Inside the callback, you can get insights concerning the mistake and the stack follow. You can likewise set what value to return inside the callback.

myErrorFunction()
.then(
(value) => print('Value: $value'),
onError: (Object e, StackTrace stackTrace) {
print(e.toString());
return 'Another value';
},
)
.then(print);

When we run the application, we ought to get the screen’s output like the underneath screen snippet.

Instance of 'MyException'
#0      myErrorFunction (file:///home/aeologic/Projects/test-dart/src/error.dart:9:53)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
Another value

Why we should using catchError?:

Future has a strategy called catchError which is utilized to deal with errors transmitted by the Future. It’s what asynchronous be compared to a catch block.

Future<T> catchError(Function onError, {bool test(Object error)?})

You need to pass a callback that will be called when the Future emits an error. Like the onError callback function of then in the previous example, the passed callback can have one or two parameters. When the callback is called, the error is passed as the first argument. If the callback accepts two parameters, the stack trace will be passed as the second argument. Below is an example without the test argument.

myErrorFunction()
.catchError((Object e, StackTrace stackTrace) {
print(e.toString());
return 'Another value';
})
.then(print);

The output of the code above should be the same as the previous example’s output.

As you can see on the signature, it likewise acknowledges a discretionary argument test. For that contention, you can pass a function that acknowledges the error as the boundary and returns a bool. On the off chance that the test argument is passed and the callback assesses to valid, the onError callback (the callback passed as the main argument) will be called. Something else, if the test callback assesses to false, the onError callback won’t be called and the returned Future finishes with a similar error, and stack follow. If the test argument isn’t passed, it defaults to a technique that returns true. The following is another model wherein the test contention is passed.

myErrorFunction()
.catchError(
(Object e, StackTrace stackTrace) {
print(e.toString());
return 'Another value';
},
test: (Object error) => error is MyException
)
.then(print);

The output of the code above should be the same as the previous example’s output.

How to Using onError?:

Future additionally, has another technique called onError. It very well may be utilized to deal with errors thrown by the Future.

Future<T> onError<E extends Object>(
FutureOr<T> handleError(E error, StackTrace stackTrace),
{bool test(E error)?})

The value you need to pass as the primary argument is like the past models, a callback work tolerating a couple of boundaries. The thing that matters is the callback work needs to return a value whose type is equivalent to the return kind of the past Future. Like catchError, it acknowledges discretionary test argument which is utilized to deal with whether the passed callback should deal with the discharged mistake or not. In any case, you can likewise indicate a particular error type to be gotten bypassing a generic sort (e.g. .onError<MyException>). All errors with an alternate errors type won’t be taken care of.

myErrorFunction()
.onError<MyException>(
(Object e, StackTrace stackTrace) {
print(e.toString());
return 'Another value';
},
test: (Object error) => error is MyException
);

The output of the code above should be the same as the previous example’s output.

Using whenComplete:

While catchError reciprocals to get block, whenComplete is what might be compared to at finally the block. Hence, if a code should be executed whether or not the Future finishes with an error or not, you can utilize whenComplete.

Future<T> whenComplete(FutureOr<void> action());

Let’s see a demo Example:

myErrorFunction()
.catchError(
(Object e, StackTrace stackTrace) {
print(e.toString());
},
test: (Object error) => error is MyException
)
.whenComplete(() { print('complete'); })
.then(print);

When we run the application, we ought to get the screen’s output like the underneath screen snippet:

Instance of 'MyException'
#0     myErrorFunction (file:///home/aeologic/Projects/test-dart/src/error.dart:9:53)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
complete

Error Handling with Try-Catch Block:

For asynchronous codes with async/await style or for non-asynchronous codes, you can utilize the try-catch-finally block, which is additionally normal in other programming dialects. Dart’s catch acknowledges it is possible that a couple of parameters. On the off chance that an error is thrown, the error will be passed as the principal argument. If the catch block acknowledges two boundaries, the stack trace will be passed as the second argument.

try {
await myErrorFunction();
} catch (e, stackTrace) {
print(e.toString());
} finally {
print('complete');
}

Conclusion:

In the article, I have explained the basic structure of the Streams And Sinks In Dart & Flutter; you can modify this code according to your choice. This was a small introduction to Streams And Sinks In Dart & Flutter On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Streams And Sinks In Dart & Flutter in your flutter projectsThat is how to deal with errors in Dart/Flutter. For non-asynchronous codes or asynchronous codes with async/await style, you can utilize the try-catch-finally block. When utilizing Future, you can pass a callback as then’s onError the argument to deal with errors. You can likewise utilize catchError and whenComplete which are the reciprocals of catch and finallylastly separately. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.