asp.net core 自定義異常處理中間件
Intro
在 asp.net core 中全局異常處理瞻赶,有時候可能不能滿足我們的需要嘴脾,可能就需要自己自定義一個中間件處理了稍途,最近遇到一個問題轩性,有一些異常棍辕,不希望記錄錯誤日志闰渔,目前主要是用戶請求取消導(dǎo)致的 TaskCanceledException
和 OperationCanceledException
異常席函。因為我的 ERROR 級別的日志會輸出到 Sentry,sentry的異常會自動發(fā)郵件提醒冈涧,如果是一些沒必要的錯誤茂附,自然不需要記錄錯誤日志,于是就想自定義一個異常處理中間件督弓,自己處理異常营曼,不將異常處理直接交給 asp.net core 的異常處理。
請求取消
請求取消導(dǎo)致的異常:
asp.net core 引入了 HttpContext.RequestAborted
來監(jiān)聽用戶取消請求(實際測試下來愚隧,并不是每次都會觸發(fā)蒂阱,還沒搞清楚怎么100%的觸發(fā)),你可以使用 HttpContext.RequestAborted
來在用戶取消請求的時候中斷后臺邏輯的處理,避免處理一些不必要的業(yè)務(wù)录煤,下面給出一個使用示例鳄厌,示例源碼
,更多詳細(xì)信息可以參考 圣杰的這篇 中斷請求了解一下
[HttpGet]
public async Task<IActionResult> GetAsync(string keyword, int pageNumber = 1, int pageSize = 10)
{
Expression<Func<Notice, bool>> predict = n => true;
if (!string.IsNullOrWhiteSpace(keyword))
{
predict = predict.And(n => n.NoticeTitle.Contains(keyword));
}
var result = await _repository.GetPagedListResultAsync(x => new
{
x.NoticeTitle,
x.NoticeVisitCount,
x.NoticeCustomPath,
x.NoticePublisher,
x.NoticePublishTime,
x.NoticeImagePath
}, queryBuilder => queryBuilder
.WithPredict(predict)
.WithOrderBy(q => q.OrderByDescending(_ => _.NoticePublishTime))
, pageNumber, pageSize, HttpContext.RequestAborted); // 直接使用 HttpContext.RequestAborted
return Ok(result);
}
// 在 Action 方法中聲明 CancellationToken妈踊,asp.net core 會自動將 `HttpContext.RequestAborted` 綁定到 CancellationToken 對象
[HttpGet]
public async Task<IActionResult> GetAsync(CancellationToken cancellationToken)
{
var result = await _repository.GetResultAsync(p => new
{
p.PlaceName,
p.PlaceIndex,
p.PlaceId,
p.MaxReservationPeriodNum
}, builder => builder
.WithPredict(x => x.IsActive)
.WithOrderBy(x => x.OrderBy(_ => _.PlaceIndex).ThenBy(_ => _.UpdateTime)), cancellationToken);
return Ok(result);
}
異常處理中間件
異常處理中間件源碼:
public class CustomExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly CustomExceptionHandlerOptions _options;
public CustomExceptionHandlerMiddleware(RequestDelegate next, IOptions<CustomExceptionHandlerOptions> options)
{
_next = next;
_options = options.Value;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (System.Exception ex)
{
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>()
.CreateLogger<CustomExceptionHandlerMiddleware>();
if (context.RequestAborted.IsCancellationRequested && (ex is TaskCanceledException || ex is OperationCanceledException))
{
_options.OnRequestAborted?.Invoke(context, logger);
}
else
{
_options.OnException?.Invoke(context, logger, ex);
}
}
}
}
public class CustomExceptionHandlerOptions
{
public Func<HttpContext, ILogger, Exception, Task> OnException { get; set; } =
async (context, logger, exception) => logger.LogError(exception, $"Request exception, requestId: {context.TraceIdentifier}");
public Func<HttpContext, ILogger, Task> OnRequestAborted { get; set; } =
async (context, logger) => logger.LogInformation($"Request aborted, requestId: {context.TraceIdentifier}");
}
可以通過配置 CustomExceptionHandlerOptions
來實現(xiàn)自定義的異常處理邏輯了嚎,默認(rèn)請求取消會記錄一條 Information 級別的日志,其他異常則會記錄一條 Error 級別的錯誤日志
你可以通過下面的示例來配置遇到請求取消異常的時候什么都不做
service.Configure(options=>
{
options.OnRequestAborted = (context, logger) => Task.CompletedTask;
});