Exceptions middleware

Error types

  • 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter
  • 401 Unauthorized – client failed to authenticate with the server
  • 403 Forbidden – client authenticated but does not have permission to access the requested resource
  • 404 Not Found – the requested resource does not exist
  • 500 Internal Server Error – a generic error occurred on the server

ExceptionHandlingMiddleware

If an unexpected error occurred, the system will automatically throw a 500 HTTP Code and the error message will hide complex details (The details will be send to the logging system. For security purpose, the user should not know details)

For example, an expected error is when we throw an HttpException in a service.

public static class ExceptionHandlingMiddleware
{
    public static IApplicationBuilder UseNativeGlobalExceptionHandler(this IApplicationBuilder app)
    {
        app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
            {
                var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                var exception = errorFeature.Error;

                HttpException error = new InternalServerException();

                if (exception is HttpException httpException)
                {
                    error = httpException;
                }

                ErrorResponse errorResponse = new()
                {
                    StatusCode = error.StatusCode,
                    Message = error.Message
                };

                context.Response.StatusCode = (int)errorResponse.StatusCode;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(errorResponse.ToJsonString());
            }));

        return app;
    }
}

Startup

Important to call this line to setup the middleware at startup:

app.UseNativeGlobalExceptionHandler();

References

results matching ""

    No results matching ""