Skip to content

Allow for registering global mutation convention exceptions mapped to a single error type #5830

@glen-84

Description

@glen-84

Product

Hot Chocolate

Is your feature request related to a problem?

Handling common exceptions requires you to apply attributes to many mutations, even if you don't require more specific error properties.

The solution you'd like

What if you could register one or more exceptions that map to the same "generic" error type?

For example:

.AddMutationConventions(options =>
{
    options.ErrorInterface<IError>();

    // These both implement `IError`.
    options.GlobalExceptions
        .Register<DomainException>();
        .Register<NotFoundException>();
}

When an exception occurs, it will be handled by Error attributes on the mutation first. If there is no matching error attribute, and the exception implements IError, then a generic error type will be returned based on the error interface.

In this way, you're not adding DomainError and NotFoundError to many mutations or every mutation, but rather a single Error type is created for handling the registered "global exceptions".

So instead of using:

[Error<DomainError>]
[Error<NotFoundError>]
[Error<NotGlobalError1>]
[Error<NotGlobalError2>]

You could just have:

[Error<NotGlobalError1>]
[Error<NotGlobalError2>]

If your error interface contains a Message and a Code, then you can do the following on any mutation:

addArticle(...) {
    article {
        # ...
    }
    errors {
        ... on Error { # Could come from a `DomainException` or a `NotFoundException`.
            message
            code
        }
    }
}

Having DomainException and NotFoundException extend a common base exception would still require you to add that error to every single mutation in your schema, so that doesn't solve the problem.

I'm aware of certain best practices like strongly-typed errors, and alternatives like result objects, but they're not always feasible, and don't always make sense.


Note that this doesn't solve the issue of libraries being able to add application-level errors that don't result in HTTP 500 results. If it were possible to raise an application-level error using middleware, for example, then that same mechanism could potentially be used to achieve something similar to the above suggestion.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions