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

编程入门 行业动态 更新时间:2024-10-23 04:37:41
本文介绍了在呈现页面之前,如何在ASP .NET Core 2.0中捕获未处理的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am trying to integrate sentry into my asp 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中捕获未处理的异常?

本文发布于:2023-11-15 14:01:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595080.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   页面   未处理   如何在   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!