feat: add custom exception unwrapping in interceptors#2484
Open
meylis1998 wants to merge 1 commit intocfug:mainfrom
Open
feat: add custom exception unwrapping in interceptors#2484meylis1998 wants to merge 1 commit intocfug:mainfrom
meylis1998 wants to merge 1 commit intocfug:mainfrom
Conversation
Add mechanism to throw custom exceptions directly from interceptors
instead of wrapping them in DioException.
- Add `throwInnerErrorOnFinish` flag to DioException
- Add `DioException.customError()` factory constructor
- Add `rejectCustomError()` method to all interceptor handlers
- Unwrap marked exceptions in fetch() final catch block
This allows callers to catch custom exception types directly:
```dart
dio.interceptors.add(InterceptorsWrapper(
onResponse: (response, handler) {
if (response.statusCode == 401) {
handler.rejectCustomError(
UnauthorizedException('Token expired'),
response.requestOptions,
);
return;
}
handler.next(response);
},
));
// Caller can now catch custom exception directly:
try {
await dio.get('/api');
} on UnauthorizedException catch (e) {
// Now works!
}
```
Closes cfug#1950
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
DioExceptionChanges
throwInnerErrorOnFinishflag toDioException(defaultfalse)DioException.customError()factory constructor for convenient creationrejectCustomError()method toRequestInterceptorHandler,ResponseInterceptorHandler, andErrorInterceptorHandlerfetch()final catch blockExample Usage
Test plan
rejectCustomError()from all three handler typesreject()still wraps inDioExceptionDioException.customError()factorycopyWith()preserving the flagcallFollowingErrorInterceptorparameterQueuedInterceptorsupportCloses #1950