errorConverter function

Middleware errorConverter({
  1. Future<Response?> onMethodNotAllowed(
    1. MethodNotAllowed
    )?,
  2. Future<Response?> onUnmatchedTarget(
    1. UnmatchedTarget
    )?,
  3. Future<Response?> onCollectionNotFound(
    1. CollectionNotFound
    )?,
  4. Future<Response?> onResourceNotFound(
    1. ResourceNotFound
    )?,
  5. Future<Response?> onRelationshipNotFound(
    1. RelationshipNotFound
    )?,
  6. Future<Response?> onError(
    1. Object,
    2. StackTrace
    )?,
})

Creates a middleware that maps server exceptions to HTTP responses.

Implementation

Middleware errorConverter({
  Future<Response?> Function(MethodNotAllowed)? onMethodNotAllowed,
  Future<Response?> Function(UnmatchedTarget)? onUnmatchedTarget,
  Future<Response?> Function(CollectionNotFound)? onCollectionNotFound,
  Future<Response?> Function(ResourceNotFound)? onResourceNotFound,
  Future<Response?> Function(RelationshipNotFound)? onRelationshipNotFound,
  Future<Response?> Function(Object, StackTrace)? onError,
}) =>
    middleware(
        onError: (error, trace, _) async => switch (error) {
              MethodNotAllowed() =>
                await onMethodNotAllowed?.call(error) ?? methodNotAllowed(),
              UnmatchedTarget() =>
                await onUnmatchedTarget?.call(error) ?? badRequest(),
              CollectionNotFound() => await onCollectionNotFound?.call(error) ??
                  notFound(OutboundErrorDocument([
                    ErrorObject(
                      title: 'Collection Not Found',
                      detail: 'Type: ${error.type}',
                    )
                  ])),
              ResourceNotFound() => await onResourceNotFound?.call(error) ??
                  notFound(OutboundErrorDocument([
                    ErrorObject(
                      title: 'Resource Not Found',
                      detail: 'Type: ${error.type}, id: ${error.id}',
                    )
                  ])),
              RelationshipNotFound() =>
                await onRelationshipNotFound?.call(error) ??
                    notFound(OutboundErrorDocument([
                      ErrorObject(
                        title: 'Relationship Not Found',
                        detail: 'Type: ${error.type}'
                            ', id: ${error.id}'
                            ', relationship: ${error.relationship}',
                      )
                    ])),
              UnsupportedMediaType() => unsupportedMediaType(),
              NotAcceptable() => notAcceptable(),
              _ => await onError?.call(error, trace) ??
                  internalServerError(OutboundErrorDocument(
                      [ErrorObject(title: 'Internal Server Error')]))
            });