Asp.net Core 全局异常处理
中间件方式
- 建立中间件处理类
- Startup.cs 中注册
- 任何Controller中的Action抛出异常均可被捕捉
在项目根目录下自建目录Middleware
新建中间件类ErrorHandlerMiddleware
,
using Newtonsoft.Json;
using System.Net;
using Uap.Exceptions;
namespace Uap.Middleware
{
/// <summary>
/// 全局错误处理中间件
/// </summary>
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var code = 0;
var message = "Unknown error";
// BadHttpRequestException,请求类错误
// ServiceException,自定义的后端处理类错误
if (ex is BadHttpRequestException)
{
code = ((BadHttpRequestException)ex).StatusCode;
message = ex.Message;
}
else if (ex is ServiceException)
{
code = (int)((ServiceException)ex).StatusCode;
message = ex.Message;
}
else
{
code = (int)HttpStatusCode.InternalServerError;
message = "Internal server error";
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = code;
return context.Response.WriteAsync(JsonConvert.SerializeObject(new { message = message }));
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2022-03-23 Spring boot Tools 4
2022-03-23 Maven