Handling exception in asp.net core?

前端 未结 2 406
面向向阳花
面向向阳花 2021-02-03 23:35

I have asp.net core application. The implementation of configure method redirects the user to \"Error\" page when there is an exception ( in non Development environment)

2条回答
  •  醉梦人生
    2021-02-04 00:05

    You can use to handle exceptions UseExceptionHandler(), put this code in your Startup.cs.

    UseExceptionHandler can be used to handle exceptions globally. You can get all the details of exception object like Stack Trace, Inner exception and others. And then you can show them on screen. Here

    Here You can read more about this diagnostic middleware and find how using IExceptionFilter and by creating your own custom exception handler.

       app.UseExceptionHandler(
                    options =>
                    {
                        options.Run(
                            async context =>
                            {
                                context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                                context.Response.ContentType = "text/html";
                                var ex = context.Features.Get();
                                if (ex != null)
                                {
                                    var err = $"

    Error: {ex.Error.Message}

    {ex.Error.StackTrace}"; await context.Response.WriteAsync(err).ConfigureAwait(false); } }); } );

    You have to also delete default setting like UseDeveloperExceptionPage(), if you use it, it always show default error page.

       if (env.IsDevelopment())
            {
                //This line should be deleted
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
    

提交回复
热议问题