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 }));
}
}
}