user9623401
user9623401

Reputation:

How to handle custom error in .NET Core app

I'm new to asp.net core and C#, sorry if my question sounds dumb, below is my code:

//startup.cs
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    app.UseExceptionHandler("/error.html");

    app.Use(async (context, next) => {
        await context.Response.WriteAsync("Hello");
        await next();
     });
     app.Run(context => {
        throw new Exception("Something has gone wrong");
     });
}

we can see that the last middleware throws an exception, so I expects to see my custom error.html page to be displayed but I still see "Hello" on the page and there is no error.html content, how come?

Upvotes: 1

Views: 712

Answers (2)

Yinqiu
Yinqiu

Reputation: 7190

The custom error page uses the above configuration.

context.Response.WriteAsync("Hello"); can block HttpHeaders, it sets HttpHeader._isReadOnly to true, and any subsequent operations on HttpHeader are invalid. So only Hello will be displayed.

If you delete the code, you will find that you still cannot reach the Error page.

That because when an exception occurs, it will take the route /errors.html to reach the corresponding custom error page.

If an exception occurs in the mvc, it can be reached normally; But when an exception occurs in the middleware, On the way to the custom error page, we pass the abnormal middleware again, so that the custom error page also produces an exception.

This is why the custom error page cannot be displayed.

If you want to throw a middleware exception, the easiest way is to use redirect instead of ExceptionHandler:

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.Use(async (context, next) => {
            try
            {
                throw new Exception("Something has gone wrong");
            }
            catch (Exception)
            {
                //await context.Response.WriteAsync("Hello");
                context.Response.Redirect("/error.html");
                await next();
            }
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Upvotes: 0

Bamdad
Bamdad

Reputation: 838

You need to add the error page middleware. Try:

app.UseDeveloperExceptionPage();

Also take a look at this for better explanation.

Upvotes: 0

Related Questions