iTranslated by AI
[Flutter] Safe Error Handling Architecture using Result Type, sealed class, and AppException
Introduction
I have struggled significantly with error handling for a long time.
In Dart, exceptions are typically handled using the try-catch-throw flow, but this has several issues:
- The type system does not indicate which function throws which exceptions.
- It is impossible to grasp the list of possible exceptions without tracing the implementation.
- In team development, strategies and granularities for error handling tend to vary among individuals.
As the product grows, these problems lead to "forgotten error handling" and "high catch-up costs" that gradually hinder development.
In this article, I will explain a design that combines these three elements to solve these issues:
Result type × sealed class × AppException
With this approach, we can:
- "Return" exceptions as values instead of "throwing" them.
- Express "where" and "what kind of errors" can occur using the type system.
I will explain this safe and traceable error handling mechanism with concrete code examples.
Target Audience
- Those developing with Flutter/Dart who feel that their error handling (try-catch) has become chaotic.
- Those who have been using
throw Exceptionindiscriminately but now want to properly redesign their error handling as the product scales. - Flutter engineers interested in designs like
Resulttypes,sealed classes, andAppException, and who want to understand them through real code examples rather than just conceptual explanations. - Those who want to establish a consistent error design from the UI to the domain and repository layers in medium to large-scale Flutter apps.
Author's Environment at Time of Writing
[✓] Flutter (Channel stable, 3.35.4, on macOS 26.0.1 25A362 darwin-arm64, locale ja-JP)
[!] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 16.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.2)
[✓] VS Code (version 1.104.3)
[✓] Connected device (5 available)
[✓] Network resources
Key Packages
- freezed
- riverpod
dependencies:
flutter_hooks: ^0.21.3+1
hooks_riverpod: ^3.0.3
riverpod_annotation: ^3.0.3
freezed_annotation: ^3.1.0
go_router: ^17.0.0
dev_dependencies:
build_runner: ^2.7.1
riverpod_generator: ^3.0.3
riverpod_lint: ^3.0.3
freezed: ^3.2.3
Sample Project
Non-Goals
This article assumes the use of Riverpod for DI (Dependency Injection). I will not be explaining Riverpod itself, so please keep that in mind.
I have covered this in a previous article, so please refer to that if you are interested.
Issues with try-catch Only Handling
Dart functions cannot express what exceptions might occur during execution through the type system (exceptions do not appear in the type).
Therefore, developers must manually track which exceptions might be thrown by:
- Reading documentation comments.
- Jumping to the definition and checking the implementation.
This is manageable for small functions, but in real-world products where the call stack is deep (e.g., UI → Service → Repository → DataSource → Network Layer), tracing the flow of exceptions carries a significant cost.
Furthermore, in team development, when creating new methods by combining existing functions, issues such as:
- Overlooking exceptions.
- Missing exceptions one was unaware of.
- Inconsistent granularity and handling of try-catch.
...can lead to bugs. As the product scales, managing, understanding, and maintaining a unified error handling strategy becomes difficult, and development costs and risks balloon unexpectedly.
Three Means of Solution
The problems mentioned above stem from the nature of Dart, where "exceptions do not appear in the type system, and it is unclear where or what might happen."
To handle this safely, this article combines the following three mechanisms:
-
sealed class (Language Feature)
Allows safe enumeration of states and exhaustive handling via pattern matching. -
Result type (Implementation Pattern)
Clearly returns success and failure as types, allowing exceptions to be handled as return values. -
AppException (App-specific Design)
A base class for managing all app-related errors under a common type.
By combining these, we can unify the design to "return" exceptions instead of "throwing" them, realizing an application design where it is clear what can happen and where, verified by the type system.
I will explain each mechanism in order.
sealed class
sealed class is a class modifier introduced in Dart 3.0. Its purpose, similar to enum, is to "group specific types together" and to enable safe pattern matching.
The differences from enum are:
- Since they are classes, they can have fields and methods.
- They can extend other classes (create subclasses).
- However, subclasses can only be created within the same file (external inheritance is prohibited).
This allows us to create a flexible and safe model where:
- We can safely check for exhaustive coverage of subclasses (cases) for a parent class (sealed).
- Each subclass can hold its own values and behaviors.
Let's look at a simple example.
// Define a sealed class (subclasses can only be created within the same file)
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Rectangle extends Shape {
final double width;
final double height;
Rectangle(this.width, this.height);
}
class Triangle extends Shape {
final double base;
final double height;
Triangle(this.base, this.height);
}
// Exhaustive checking is possible with pattern matching
double calculateArea(Shape shape) {
return switch (shape) {
Circle(radius: final r) => 3.14 * r * r,
Rectangle(width: final w, height: final h) => w * h,
Triangle(base: final b, height: final h) => 0.5 * b * h,
// ↑ A compilation error occurs unless all subclasses are covered
};
}
In this example, we define the child classes Circle, Rectangle, and Triangle for the parent class Shape. Because the switch expression requires exhaustive coverage of all cases to avoid a compilation error, it prevents missing any cases when new subclasses are added.
The Result type, discussed later, also uses this sealed class mechanism to handle Success and Failure together.
Result Type
The Result type is used to represent the result of an operation in two categories: Success and Failure.
Although Dart does not have a standard Result type, it can be safely implemented using sealed class.
A function that returns a Result type can explicitly indicate through its type that "this function may return not only success but also failure."
Consequently, the caller is forced to handle both Success and Failure, ensuring no cases are overlooked.
This concept is not limited to Dart; it is a pattern adopted by many modern languages:
- Swift (
Result<T, Error>) - Kotlin (
Result<T>) - Rust (
Result<T, E>)
Rust's Result is particularly powerful, as it embodies a culture of "chaining operations using the Result type instead of exceptions," becoming the cornerstone of a design where errors are explicitly stated in function return values.
AppException
Every exception in Dart is created by extending Exception, but treating them as is often results in a lack of information, such as "what kind of error it is" or "what should be displayed on the screen."
Therefore, in the application, we wrap all exceptions in a common AppException to handle them.
By consolidating app-specific information such as:
- Error code
- User-facing message
- Identifier for log output
- Handling strategy (should it be retried, is it fatal, etc.)
...into AppException, we gain several benefits:
- Unified handling of exceptions.
- Prevention of overlooking specific exception handling.
- Easier judgment by the UI layer on "what should be displayed."
- Improved monitoring, alerting, and log analysis.
Furthermore, by prohibiting raw Exceptions thrown by external libraries or SDKs from propagating to higher layers and ensuring they are converted to AppException, we can prevent accidents where "unexpected exceptions reach the UI."
Specific Implementation
From here, I will explain how to implement this by combining the mechanisms discussed above.
Defining the Result Type
While the Result type can be defined directly as a sealed class, this time we will use the freezed package. Using Freezed is highly compatible with the Result type as it automatically generates == and toString methods.
/// Result type representing the success or failure of an operation
@freezed
sealed class Result<T, E extends Exception> with _$Result<T, E> {
/// Success
const factory Result.success(T data) = Success<T, E>;
/// Failure
const factory Result.failure(E error) = Failure<T, E>;
}
The key lies in how the class generics are specified:
- T: Represents the type of the return value when the operation is successful.
- E extends Exception: Represents the type of the exception upon failure, permitting only those that extend
Exception. This creates a constraint to handle only "business errors" that should be managed by application logic, and ensures thatErrortypes that shouldn't be handled (likeStackOverflowError) are not mixed intoResult.
Defining Application Exceptions with AppException
Next, we define the base class for exceptions handled in the application as AppException.
/// Base exception class used throughout the application
abstract class AppException implements Exception {
AppException(this.type);
final AppExceptionType type;
String get prefix => type.prefix;
int get code => type.code;
String get message => type.message;
@override
String toString() => '[$prefix] $code: $message';
}
There are two main points:
- Use the
abstractmodifier to prohibit direct instantiation of this class.AppExceptionis intended as a common parent for exceptions within the app, not for throwing directly. By requiring concrete exceptions (likeSaveUserPermissionException) to be created as subclasses, we prevent ambiguity regarding the meaning and origin of errors. - Consolidate supplementary information into
AppExceptionTypeto manage exception definitions centrally. By grouping exception names, codes, and messages into anenum, we gain:- Prevention of code duplication.
- Easier editing of wording.
- Forced adherence to "writing to the enum when adding an exception."
This ensures a unified exception design across the entire product.
Error codes, in particular, must be unique (useful when users report errors), making this enum-based design an excellent fit.
/// Enum for central management of error definitions
enum AppExceptionType {
// Excerpt
// ...
saveUserStorage(
prefix: 'SaveUserStorageException',
code: 2001,
message: 'Insufficient storage capacity.',
),
saveUserPermission(
prefix: 'SaveUserPermissionException',
code: 2002,
message: 'No write permissions.',
),
saveUserUnexpected(
prefix: 'SaveUserUnexpectedException',
code: 2099,
message: 'An unexpected error occurred.',
),
// ....
;
const AppExceptionType({
required this.prefix,
required this.code,
required this.message,
});
final String prefix;
final int code;
final String message;
}
Grouping Function Exceptions with sealed class
Next, we will group the exceptions that a function might return using a sealed class. In this example, we will group the exceptions for the saveUser function in UserRepository.
/// Base class for the grouping, extending AppException
sealed class SaveUserException extends AppException {
SaveUserException(super.type);
}
// The following child classes extend SaveUserException,
// thus they also implicitly inherit from AppException.
class SaveUserStorageException extends SaveUserException {
SaveUserStorageException(super.type);
}
class SaveUserPermissionException extends SaveUserException {
SaveUserPermissionException(super.type);
}
class SaveUserUnexpectedException extends SaveUserException {
SaveUserUnexpectedException(super.type);
}
First, we define the parent class SaveUserException. By having it extend AppException at this stage, the subsequent child classes like SaveUserStorageException are forced to be compatible with AppException.
Defining Repository Methods Using the Result Type
The preparations are complete. Now, we will implement the function using the Result type and the sealed class SaveUserException defined above.
First, for the function's return type, we use a type alias to define an alternative name to avoid verbosity. This makes the type definition easier to read and clearly expresses the intention that "the saveUser function returns a SaveUserResult" in the code.
/// Return type for SaveUser
typedef SaveUserResult = Result<User, SaveUserException>;
The generics for Result<User, SaveUserException> have the following meanings:
- Left side:
User
The type of the value returned when processing completes successfully. - Right side:
SaveUserException
The type of the exception returned in case of failure (the parent of the group).- Child classes such as
SaveUserStorageExceptionandSaveUserPermissionExceptionare all included here.
- Child classes such as
Next, we define the saveUser(User user) function with the above type as its return value.
class UserRepository {
/// Saves user information locally
Future<SaveUserResult> saveUser(User user) async {
try {
// Assume storage logic (e.g., SharedPreferences or Isar) occurs here
await Future<void>.delayed(const Duration(milliseconds: 100));
// Successfully saved
return Result.success(user);
} on StorageException {
return Result.failure(
SaveUserStorageException(AppExceptionType.saveUserStorage),
);
} on PermissionException {
return Result.failure(
SaveUserPermissionException(AppExceptionType.saveUserPermission),
);
} on Exception {
return Result.failure(
SaveUserUnexpectedException(AppExceptionType.saveUserUnexpected),
);
}
}
// ...
}
In the repository layer, we perform standard try-catch exception handling.
- Success path:
When saving is successful, we returnResult.success(user)as is. - Failure path:
We catch exceptions in their respective blocks, convert them to the correspondingAppException(such asSaveUserStorageException), and return them asResult.failure(exception).
One thing to note here is the final on Exception{} block. While not strictly necessary if you account for every possible Exception, it is recommended to catch and convert "unknown errors" if there are cases you aren't sure about or want to handle generally for now.
Also, notice that I am explicitly passing the AppExceptionType at the location where I am catching the exception.
} on StorageException {
return Result.failure(
SaveUserStorageException(AppExceptionType.saveUserStorage),
);
// ...
This is done to "quickly pinpoint the origin of an error using the error code" in actual operation.
For example, in user support inquiries or Firebase Crashlytics logs, an error code (e.g., 2001) is usually provided.
- By searching for that error code
2001in the editor, you find the definition forAppExceptionType.saveUserStorage. - By tracing the references of
saveUserStorage, you can immediately identify whichcatchblock throws that error (in this case, insidesaveUser).
By designing it such that the AppExceptionType is not fixed within the exception class itself, but is passed at the actual point of conversion, you can trace in a straight line using only editor search:
- "Which code corresponds to this..."
- "...which
enumdoes it match..." - "...and exactly which line of which function is throwing the final error?"
Handling when calling a function that returns a Result type
Below is an example of calling the saveUser function from the UI layer.
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () async {
// New user (assuming a user has been input)
const newUser = User(
id: 'generated-id',
name: 'Steven Gerard',
email: 'steven.gerard@example.com',
);
// Execute save user info process
final repository = ref.read(userRepositoryProvider);
final result = await repository.saveUser(newUser);
// Display message based on result
late final String message;
switch (result) {
case Success(data: final user):
message = 'User ${user.name} created successfully!';
case Failure(error: final error):
final description = switch (error) {
SaveUserStorageException() =>
'💽 Storage Error: ${error.message}',
SaveUserPermissionException() =>
'✍️ Permission Error: ${error.message}',
SaveUserUnexpectedException() =>
'❓ Unexpected Error: ${error.message}',
};
message = 'Error creating user: $description';
}
if (context.mounted == false) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(message)));
},
),
Since saveUser returns Result<User, SaveUserException>, the UI layer must handle both the Success and Failure cases using switch (result):
-
Success(data: final user): Invoked upon successful saving;usercontains the saved user information. -
Failure(error: final error): Invoked upon failure;errorcontains theSaveUserException(or its subclass).
When a failure occurs, we use switch (error) to display specific messages for different error types:
-
SaveUserStorageExceptionfor storage issues -
SaveUserPermissionExceptionfor permission issues -
SaveUserUnexpectedExceptionfor other issues
The benefits of this handling approach are:
-
No need to write
try-catchin the UI: Since exceptions are converted toResult.failurein the repository layer, the UI layer only needs toswitchon theResultto determine whether it was a success or a specific error. -
Type-safe awareness of potential failures: Because the error type is defined as a
SaveUserException(asealed class), you can exhaustively handle all error cases within theswitch (error)block. If you add a new error type, the compiler will notify you, preventing "unhandled exceptions."
Conclusion
In this article, I introduced an error handling design that combines three mechanisms to address the "frustration that exceptions do not appear in types" in Dart/Flutter:
- Using the
Resulttype to explicitly declare "success" and "failure." - Using
sealed classto group "possible errors" for specific functions. - Using
AppException/AppExceptionTypeto centralize error management.
Key takeaways summarized:
- By returning exceptions as values rather than throwing them, you can tell from the types where and what kind of errors may occur.
- By grouping exceptions per function (e.g.,
SaveUserException), you can aggregate all "failures possible in this function" in one place. - By utilizing
AppExceptionandAppExceptionType, you can organize and handle error codes, messages, and logging information effectively. - In the UI layer, instead of
try-catch, you can exhaustively handle success, failure, and error types usingswitch (result)/switch (error).
Of course, this design is not the "only absolute truth." Depending on app scale, team preference, or existing codebases, you can:
- Start by adopting the
Resulttype in just a few Repositories. - Introduce
AppExceptionTypefirst to start organizing your exceptions. - Gradually move toward this style starting with new features.
Even a phased introduction can be quite effective.
Once you step beyond "just throw Exception" and start expressing:
- Which layer
- What kind of failure might happen
- Who handles it and how
using code and types, the outlook of your exception design will gradually become much clearer.
The sample project for this article is free to clone and modify. Feel free to try it out by applying it to your own projects, asking yourself:
"What is the exception group for this function?"
"WhichAppExceptionTypeshould this error be classified under?"
I hope that even a small part of this provides a hint to make your project's error handling easier and safer.
Continued: Connecting multiple Result types
This article focused on the error design for a single process using the "Result type × sealed class × AppException" pattern.
In actual applications, you will likely encounter further challenges regarding "how to chain multiple Result types" or "how to reduce nested structures."
I have written a follow-up article that organizes these topics alongside functional styles like mapError and flatMap. Please take a look if you are interested.
Discussion