Skip to content

No-exceptions: approach suggestion #1

@YuriyDurov

Description

@YuriyDurov

Hello @ericsink!
I have this nuget package. IMO it provides a more straightforward way to map exceptions to error codes.

So, instead of something like

case Exception1: return 1;
case Exception2: return 2;

You can do

return exception.StatusCode;

The idea is that the exception carries the error code - and you can then display this error code in the top-level handler. All the other exceptions (the ones we don't control) are automatically mapped to "Internal error" status code.

Or if you don't like this specific mapping, you can have some other logic with a custom handler.

The package was initially created to be used in Asp.Net Core, but now it can work in other environments just as well. It just doesn't have handlers for stuff like NativeAOT, but it is not hard to implement the handler yourself, especially since the samples are provided.

There is no wiring to neither Asp.Net Core, nor even HttpStatusCodes. It was intentionally designed in a way to be used in any environment. All the Asp.Net-specific code is in a separate package.

The package also allows packing more stuff into the exception. I call this 'Payload'. Seems like a pattern that could be used here. Like, not returning 'the whole' exception, just 'the payload'. And the payload can be populated by whoever is throwing that exception.

As for the exceptions we don't control - the handler can simply add the exception.Message as one of the payload fields. This is also what I am doing when using this package in Asp.Net Core.

You can then probably pack the payload into some kind of response model and simply return it. And use the StatusCode as, well, your status code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions