Skip to content

Commit e44c28d

Browse files
authored
Enhance error handling documentation in README (#864)
Updated error handling section with additional information on client-level error handling using CallAdapters.
1 parent 393ec88 commit e44c28d

1 file changed

Lines changed: 41 additions & 1 deletion

File tree

README.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ You can define headers at the `@RestApi` level that will be automatically includ
386386

387387
### Error Handling
388388

389-
`catchError(Object)` should be used for capturing the exception and failed response. You can get the detailed response info from `DioError.response`.
389+
`catchError(Object)` can be used for capturing the exception and failed response. You can get the detailed response info from `DioError.response`.
390390

391391
```dart
392392
client.getTask('2').then((it) {
@@ -405,6 +405,46 @@ client.getTask('2').then((it) {
405405
});
406406
```
407407

408+
409+
Errors can also be caught and handled at the client level using CallAdapters. For example:
410+
411+
```dart
412+
class ErrorAdapter<T> extends CallAdapter<Future<T>, Future<T>> {
413+
@override
414+
Future<T> adapt(Future<T> Function() call) {
415+
try {
416+
return call();
417+
} catch (exception) {
418+
// Handle the exception and throw whatever exception you want
419+
throw MyCustomException();
420+
}
421+
}
422+
}
423+
424+
@RestApi(callAdapter: ErrorAdapter)
425+
abstract class RestClient {
426+
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
427+
428+
@GET('/user')
429+
Future<User> getUser();
430+
}
431+
```
432+
433+
If you need to handle errors individually per API method instead of at the client level:
434+
435+
``` dart
436+
@RestApi()
437+
abstract class RestClient {
438+
factory RestClient(Dio dio, {String? baseUrl}) = _RestClient;
439+
440+
@GET('/user')
441+
@UseCallAdapter(ErrorAdapter)
442+
Future<User> getUser();
443+
}
444+
```
445+
446+
447+
408448
### Relative API baseUrl
409449

410450
If you want to use a relative `baseUrl` value in the `RestApi` annotation of the `RestClient`, you need to specify a `baseUrl` in `dio.options.baseUrl`.

0 commit comments

Comments
 (0)