中間件方式
- 建立中間件處理類
- 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 }));
}
}
}