asp.net core 全局捕获异常,返回一个统一的 JSON(包含错误信息和状态码)
1. 创建一个类文件用于定义全局异常捕获操作
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace WebApplication1.Excepion
{
/// <summary>
/// 全局异常捕获
/// </summary>
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(RequestDelegate netx, ILogger<ExceptionHandlingMiddleware> logger)
{
_logger = logger;
_next = netx;
}
/// <summary>
/// 此方法名不可自定义名字,不然报错
/// 没有公共'Invoke'或'InvokeAsync'方法,用于执行中间件。”
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext context)
{
try
{
// 继续传递给下一个中间件或控制器
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex.Message, "全局捕获到的错误");
context.Response.ContentType = "application/json"; //不设置类型返回就会乱码
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var errorResponse = new
{
Code = context.Response.StatusCode,
Msg = "服务器发生错误请联系管理员",
ErrorMsg = ex.Message,
};
//将对象转为json
var result = JsonSerializer.Serialize(errorResponse);
await context.Response.WriteAsync(result);
}
}
}
}
2. 将自定义的全局捕获进行注册,以及测试是否能成功捕获
3.测试结果