DevDev
DevDev

Reputation: 313

Owin doesn't send any response if an unhandled exception is met

Is there a way to send an HTTP response with 500 status code if Owin finds an unhandled exception in the application?

Upvotes: 0

Views: 90

Answers (1)

jumuro
jumuro

Reputation: 1532

For global error handling you can write a custom and simple middleware that just pass the execution flow to the following middleware in the pipeline but inside a try block.

If there is an unhandled exception in one of the following middlewares in the pipeline, it will be captured in the catch block:

public class GlobalExceptionMiddleware : OwinMiddleware
{
    public GlobalExceptionMiddleware(OwinMiddleware next) : base(next)
    { }

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);
        }
        catch (Exception ex)
        {
            // your handling logic, for example set HTTP status code to 500 in response
        }
    }
}

In the Startup.Configuration() method, add the middleware in first place to the pipeline if you want to handle exceptions for all other middlewares.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<GlobalExceptionMiddleware>();
        //Register other middlewares
    }
}

If you are using Web API middleware, you need to implement IExceptionHandler interface and replace it in configuration. Please see my response to a related question for detailed information.

I hope it helps.

Upvotes: 1

Related Questions