Nick
Nick

Reputation: 1424

Trigger exception handler (with status code) from middleware

I'm trying to trigger an exception (handled by /Error) from a middleware in ASP.NET Core 3.1.

Exception handler is registered in Startup.cs (as shown below) without app.UseDeveloperExceptionPage(), and works well otherwise.

app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error", "?statusCode={0}");

But how do I trigger an exception (with an HTTP status code) from a middleware's Invoke method?

Update (solution): I mainly wanted to raise an exception from a custom middleware, but also pass a status code to the exception handler (/Error). I got it working with this code in the middleware:

public async Task Invoke(HttpContext context)
{
    if (context?.Request?.Path.Value.StartsWith("/error"))
    {
        // allow processing of exception handler
        await _next(context);
        return;
    }

    // skip processing, and set status code for use in exception handler
    context.SetEndpoint(endpoint: null);
    context.Response.StatusCode = 503;
}

Upvotes: 1

Views: 1987

Answers (2)

Nick
Nick

Reputation: 1424

I mainly wanted to raise an exception from a custom middleware, but also pass a status code to the exception handler (/Error). I got it working with this code in the middleware:

public async Task Invoke(HttpContext context)
{
    if (context?.Request?.Path.Value.StartsWith("/error"))
    {
        // allow processing of exception handler
        await _next(context);
        return;
    }

    // skip processing, and set status code for use in exception handler
    context.SetEndpoint(endpoint: null);
    context.Response.StatusCode = 503;
}

Upvotes: 0

Brando Zhang
Brando Zhang

Reputation: 27962

According to the document, if the server catches an exception before response headers are sent, the server sends a 500 - Internal Server Error response without a response body.

If the server catches an exception after response headers are sent, the server closes the connection.

Requests that aren't handled by the app are handled by the server.

Any exception that occurs when the server is handling the request is handled by the server's exception handling. The app's custom error pages, exception handling middleware, and filters don't affect this behavior.

If you directly throw the exception at the application start, it will not goes to the exception handler.

Like below middleware:

        app.Use(async (context, next) =>
        {
  
                throw new ArgumentException("aaa");
     
            await next();
        });

If you throw the exception is thrown after the application has completely started, it will go to the exception handler like below example. If you type home/privacy in your url, you will find it goes to the exception handler page.

     app.Use(async (context, next) =>
        {
            if (context.Request.Path == "/Home/Privacy")
            {
                throw new ArgumentException("aaa");
            }
            await next();
        });

Result:

enter image description here

Upvotes: 1

Related Questions