進入了.net core時代,開始有了Middleware
所以我們可以從startup加入一個ErrrorHandler的Middleware
於是建了一個處理錯誤的class
public class ErrorHandlerMiddleware {private ILogger _logger = NLog.LogManager.GetCurrentClassLogger();
private readonly RequestDelegate _next;public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
response.StatusCode = (int)HttpStatusCode.OK;
response.ContentType = "application/json";
var result = new ResponseBase<string>();
result.Message = error.GetErrorMessage();
result.StatusCode = EnumStatusCode.Fail;await response.WriteAsync(JsonSerializer.Serialize(result));
}
}
}
之後再到startup.cs加入這一個class就可以全域處理錯誤
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)所以Controller發生了錯誤直接會在這邊統一處理,就不用每個Controller寫try catch 是否方便了許多
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseMiddleware<ErrorHandlerMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
沒有留言:
張貼留言