在呈现页面之前,如何在ASP .NET Core 2.0中捕获未处理的异常? [英] How do I catch unhandled exceptions in ASP .NET Core 2.0 before the page is rendered?

查看:232
本文介绍了在呈现页面之前,如何在ASP .NET Core 2.0中捕获未处理的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 sentry 集成到我的asp .net核心应用中。在服务器将500个ASP Net Core 2.0中的异常抛出之前,我似乎找不到直接的答案。

I am trying to integrate sentry into my asp .net core app. I can't seem to find a straight answer how to catch the exception before the server throws 500 in asp net core 2.0.

我已经搜索了官方文档。非开发模式。

I've searched official docs. Non-development mode.

推荐答案

这里是异常处理中间件的一个示例。

Here is an example of exception handling middleware. It returns custom verbiage with the 500 status code.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Serilog;
using System;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Foo
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate next;

        public ExceptionHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await handleExceptionAsync(context, ex);
            }
        }

        private static async Task handleExceptionAsync(HttpContext context, Exception exception)
        {
            string errorCode = calculateErrorCode(context.TraceIdentifier);
            string message = string.Format("An unhandled exception occurred; please contact the help desk with the following error code: '{0}'  [{1}]", errorCode, context.TraceIdentifier);

            Log.Error(exception, message);            

            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            await context.Response.WriteAsync(message);
        }        

        private static string calculateErrorCode(string traceIdentifier)
        {
            const int ErrorCodeLength = 6;
            const string CodeValues = "BCDFGHJKLMNPQRSTVWXYZ";

            MD5 hasher = MD5.Create();

            StringBuilder sb = new StringBuilder(10);

            byte[] traceBytes = hasher.ComputeHash(Encoding.UTF8.GetBytes(traceIdentifier));

            int codeValuesLength = CodeValues.Length;

            for (int i = 0; i < ErrorCodeLength; i++)
            {
                sb.Append(CodeValues[traceBytes[i] % codeValuesLength]);
            }

            return sb.ToString();
        }
    }

    public static class ExceptionHandlingMiddlewareExtensions
    {
        public static IApplicationBuilder UseApiExceptionHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionHandlingMiddleware>();
        }
    }
}

在Startup.cs中配置

Configure in Startup.cs

app.UseApiExceptionHandler();

这篇关于在呈现页面之前,如何在ASP .NET Core 2.0中捕获未处理的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆