1

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;
}
0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I mainly wanted to raise an exception but also pass a status code to the exception handler. I got it working with a slightly different approach (solution in update above).
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.