normalizeError function

BaseException normalizeError(
  1. Object error,
  2. StackTrace stack, {
  3. String? source,
  4. Severity defaultSeverity = Severity.error,
})

Normalizes arbitrary errors into your BaseException hierarchy.

Mapping strategy:

  • If already BaseException => passthrough
  • If Flutter PlatformException => PlatformOperationException.fromPlatformException
  • If FormatException/type issues in parser => ParsingException (callers should prefer parser)
  • Fallback => UnexpectedException

Implementation

BaseException normalizeError(
  Object error,
  StackTrace stack, {
  String? source,
  Severity defaultSeverity = Severity.error,
}) {
  if (error is BaseException) return error;

  if (error is service.PlatformException) {
    return PlatformOperationException.fromPlatformException(
      error,
      operation: source ?? 'unknown_operation',
    );
  }

  if (error is FormatException) {
    return ParsingException(
      rawData: null,
      targetType: 'unknown',
      cause: error,
      stack: stack,
    );
  }

  return UnexpectedException(
    userMessage: 'An unexpected error occurred',
    devMessage:
        source != null ? 'Unexpected error in $source' : 'Unexpected error',
    cause: error,
    stack: stack,
    severity: defaultSeverity,
    metadata: {
      if (source != null) 'source': source,
    },
  );
}