Exception Converter

The ExceptionConverter class allows you to map a specific Exception to a particular Failure object. While a single ExceptionConverter may not be very useful on its own, you can use a group of exception converters together in an ExceptionConverterSuite to run a task and automatically convert any exceptions that are thrown into the appropriate Failure object.

To create an Exception Converter, create a class that extends the ExceptionConverter class:

/// A custom exception converter for converting a [SocketException] to a
/// [NetworkFailure] if an error occurs.
///
/// If no exception is caught, then [T] is returned.
class SocketExceptionConverter<T>
    extends ExceptionConverter<SocketException, T> {
  const SocketExceptionConverter();

  @override
  Failure convert({
    required SocketException exception,
    StackTrace? stackTrace,
    CodenicLogger? logger,
    MessageLog? messageLog,
  }) {
    if (logger != null && messageLog != null) {
      // Optional: you can log the exception here if needed
      logger.wtf(messageLog, error: exception, stackTrace: stackTrace);
    }

    return const NetworkFailure();
  }
}

Last updated