如何在呈现页面之前在ASP .NET Core 2.0中捕获未处理的异常?

时间:2018-03-12 17:43:23

标签: asp.net .net .net-core

我正在尝试将sentry集成到我的asp .net核心应用中。在服务器在asp net core 2.0中抛出500之前,我似乎无法找到如何捕获异常的直接答案。

我搜索过官方文档。非开发模式。

1 个答案:

答案 0 :(得分:1)

以下是异常处理中间件的示例。它返回500状态代码的自定义词汇。

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中配置

app.UseApiExceptionHandler();