UserException class
The UserException is an immutable class representing an error the user could fix, like wrong typed text, or missing internet connection.
Async Redux will automatically capture UserExceptions to show them in
dialogs created with UserExceptionDialog or other UI you define in your
widget tree (see the explanation in the docs).
An UserException may have a message or an error code (if you provide both, the message will be ignored), as well as an optional reason, which is a more specific text that explains why the exception happened. For example:
throw UserException('Invalid email', reason: 'Must have at least 5 characters.');
Method titleAndContent returns the title and content used in the error dialog. If the exception has both a message an a reason, the title will be the message, and its content will be the reason. Otherwise, the title will be empty, and the content will be the message.
Alternatively, if you provide a numeric code instead of a message. In this case, the message of the exception will be the one associated with the code (see translateCode and codeTranslations) for more details.
The following methods and fields are available only in the async_redux package
(for Flutter), and are not available for Dart-only code:
-
Method
addCallbacksis used to addonOkandonCancelcallbacks to the UserException. TheonOkcallback will be called when the user taps OK in the error dialog. TheonCancelcallback will be called when the user taps CANCEL in the error dialog. If the exception already had callbacks, the new callbacks will be merged with the old ones, and the old callbacks will be called before the new ones. -
Field
onOkis a callback to be called when the user presses the "Ok" button in the error dialog. -
Field
onCancelis a callback to be called when the user presses the "Cancel" button in the error dialog. -
Method
addCauseadds the givencauseto the UserException. Note the addedcausewon't replace the original cause, but will be added to it. If the addedcauseis anull, it will return the current exception, unchanged. If the addedcauseis a String, the addReason method will be used to return the new exception. If the addedcauseis a UserException, the mergedWith method will be used to return the new exception. If the addedcauseis any other type, including any other error types, it will be set as the propertyhardCauseof the exception. The hard cause is meant to be some error which caused the UserException, but that is not a UserException itself. For example, ifint.parse('a')throws aFormatException, thenthrow UserException('Invalid number').addCause(FormatException('Invalid input')). will set theFormatExceptionas the hard cause. -
Field
hardCausethe hard cause of the exception, if any, that may have been set by the methodaddCause. -
Method
addPropsadds key-value pair properties to the UserException. If the exception already had properties, the newpropswill be merged with the old ones. -
Field
propsis the properties added to the exception, if any. They are an immutable-map of key-value pairs, of typeIMap<String, dynamic>. To read the properties, use the[]operator, like this:exception.props['key']. If the key does not exist, it will returnnull.
Usage:
UserException(message, code: code, reason: reason)
.addCallbacks(onOk: onOk, onCancel: onCancel)
.addCause(cause)
.withProps(props);
Example:
throw UserException('Invalid number')
.addCause(FormatException('Invalid input'))
.addProps({'number': 42}))
.addCallbacks(onOk: () => print('OK'), onCancel: () => print('CANCEL'));
You can define a special Matcher for your UserException, to use in your
tests. Create an test util file with this code:
import 'package:matcher/matcher.dart';
const Matcher throwsUserException = Throws(const TypeMatcher<UserException>());
Then use it in your tests:
expect(() => someFunction(), throwsUserException);
- Implemented types
- Implementers
- Available extensions
Constructors
- UserException(String? message, {int? code, String? reason, bool ifOpenDialog = true, String? errorText})
-
Creates a UserException, given a message
messageof type String, areasonof type String or UserException, and an optional numericcode. All fields are optional, but usually at least themessageorcodeis provided.const -
UserException.fromJson(Map<
String, dynamic> json) -
Creates a UserException instance from a JSON map.
This is compatible with Serverpod.
factory
Properties
- code → int?
-
Optionally, instead of message we may provide a numeric code.
This code may have an associated message which is set in the client.
final
- errorText → String?
-
Some text to be displayed in the UI element that is responsible for the error.
For example, a text field could show this text in its
errorTextproperty. When building your widgets, you can get the errorText from the failed action:String errorText = context.exceptionFor(MyAction)?.errorText.final - hardCause → Object?
-
Available on UserException, provided by the UserExceptionAdvancedExtension extension
The hard cause is some error which caused the UserException, but that is not a UserException itself. For example:int.parse('a')throws aFormatException. Then:throw UserException('Invalid number').addCause(FormatException('Invalid input')). will have theFormatExceptionas the hard cause. Note: If a UserException is passed as the hard cause, it will be added with addCause, and will not become the hard cause. In other words, a UserException will never be a hard cause.no setter - hashCode → int
-
The hash code for this object.
no setteroverride
- ifOpenDialog → bool
-
If
true, the UserExceptionDialog will show in the dialog or similar UI. Iffalseyou can still show the error in a different way, usually showing errorText in the UI element that is responsible for the error.final - message → String?
-
Some message shown to the user.
final
- noDialog → UserException
-
This exception should NOT open a dialog.
Still, the error may be shown in a different way, usually showing errorText
somewhere in the UI.
This is the same as doing:
.withDialog(false).no setter - onCancel → VoidCallback?
-
Available on UserException, provided by the UserExceptionAdvancedExtension extension
TheonCancelcallback of the exception, ornullif it was not defined.no setter - onOk → VoidCallback?
-
Available on UserException, provided by the UserExceptionAdvancedExtension extension
TheonOkcallback of the exception, ornullif it was not defined.no setter -
props
→ IMap<
String, dynamic> -
Available on UserException, provided by the UserExceptionAdvancedExtension extension
The properties added to the exception, if any. They are an immutable-map of typeIMap, of key-value pairs. To read the properties, use the[]operator, like this:no setter - reason → String?
-
Another text which is the reason of the user-exception.
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
addCallbacks(
{VoidCallback? onOk, VoidCallback? onCancel}) → UserException -
Available on UserException, provided by the UserExceptionAdvancedExtension extension
Adds callbacks to the UserException. -
addCause(
Object? cause) → UserException -
Available on UserException, provided by the UserExceptionAdvancedExtension extension
Returns a UserException from the current one, by adding the givencause. Note the addedcausewon't replace the original cause, but will be added to it. -
addProps(
Map< String, dynamic> ? moreProps) → UserException -
Available on UserException, provided by the UserExceptionAdvancedExtension extension
AddsmorePropsto the properties of the UserException. If the exception already had props, the newmorePropswill be merged with those. -
addReason(
String? reason) → UserException -
Returns a new UserException, copied from the current one, but adding the given
reason. Note the addedreasonwon't replace the original reason, but will be added to it. -
copyWith(
{String? message, int? code, String? reason, bool? ifOpenDialog, String? errorText}) → UserException - Returns a new instance with some fields replaced by new values. This is compatible with Serverpod.
-
mergedWith(
UserException? anotherUserException) → UserException -
Returns a new UserException, by merging the current one with the given
anotherUserException. This simply means the givenanotherUserExceptionwill be used as part of the reason of the current one. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
titleAndContent(
) → (String, String) - Based on the message, code and reason, returns the title and content to be used in some UI to show the exception the user. The UI is usually a dialog or toast.
-
toJson(
) → Map< String, dynamic> - Converts the exception into a JSON map. This is compatible with Serverpod.
-
toString(
) → String -
A string representation of this object.
override
-
withDialog(
bool ifOpenDialog) → UserException - Defines if this exception should open a dialog or not. If not, it will be shown in a different way, usually showing errorText somewhere in the UI.
-
withErrorText(
String? newErrorText) → UserException -
Adds (or replaces, if it already exists) the given
newErrorText. If thenewErrorTextisnullor empty, it will remove the errorText.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
override
Static Properties
-
codeTranslations
↔ Translations<
dynamic, Map< ?StringLocale, StringTranslated> , Map<dynamic, StringTranslated> , dynamic> -
If you use error codes, you may provide their respective text messages here,
by providing a
Translationsobject from thei18n_extensionpackage. You can only provide messages in English, or in multiple other languages.getter/setter pair - defaultJoinString ↔ String Function()
-
The default text to join the reasons in a string.
You can change this variable to inject another way to join them.
getter/setter pair
- joinCauses ↔ String Function(String? first, String? second)
-
Joins the given strings, such as the second is the reason for the first.
Will return a message such as "first\n\nReason: second".
You can change this variable to inject another way to join them.
getter/setter pair
- translateCode ↔ String Function(int?)
-
The translateCode method is called to convert error codes into text messages.
If you are using use the
i18n_extension, you may provide codeTranslations. If you are NOT using thei18n_extension, you can instead modify the translateCode method to return a string from the code in any way you want.getter/setter pair
Static Methods
-
setLocale(
String? localeStr) → void - Use this to set the locale used by method titleAndContent to translate the text "Reason:" used to explain the chain of reasons in the UserException.