Error handling topic
It's Essential
Any errors that may occur in a StateX object is directed to its function, onError(). Depending on whether it's a particular exception that can be handled, or an unanticipated error that will cause the app to terminate, the onError() will be the first to receive the details. This is an opportunity for you to close any critical resources or services and 'fail gracefully' before the error is then recorded in the device's logs.
/// This function is called when an error occurred.
void onError(FlutterErrorDetails details) {}
Seeing Red | On Error | Control Your Error |
Seeing Red
In the first screenshot below, is of the FloatingActionButton widget containing the error. As you see, an Exception is deliberately thrown when the button is tapped. (Note, the error is not thrown when running in a test environment.) Such an error would normally cause Flutter's default handler, dumpErrorToConsole, to record the error in the device's error logs. If the error had occurred while attempting to display a widget, it would further present a description of the error on a 'red screen' when in development, and on a gray screen when in production.
On Error
In this case, the error logs are written to, but the count still incremented. Flutter's FlutterError.onError was assigned an error handler that allows the State object to possibly address its errors. In the second screenshot below, the onError() function determines the incrementation was interrupted and so attempts once again. This is a very simple example, but you can see the potential to better handle errors in your own app.
page_01.dart | page_01.dart |
---|
Control Your Error
The onError() function is supplied by the mixin, StateXonErrorMixin. The StateX class utilizes it, but the StateXController does not. However, it can if the need arises. Care must be taken when implementing the onError() function in Controllers as one may catch an error intended for another. But if used judiciously, there may be instances where a controller should catch and handle any failed operation of its own doing.
The first screenshot below demonstrates how you might seek out such controllers when the '+' button error occurred. The StateX object goes through its controllers and calls those with a onError() function of their own.
page_01.dart | yet_another_controller.dart |
---|
Further information under the topic: AppStateX class
Classes
-
StateX<
T extends StatefulWidget> Get started StateX class Using FutureBuilder Error handling Testing Event handling - The extension of the State class.
Mixins
- RecordExceptionMixin StateX class Error handling
- Record an exception for review by the developer
- StateXonErrorMixin StateX class Error handling
- Supply an 'error handler' routine if something goes wrong. It need not be implemented, but it's their for your consideration.