core 自定义异常处理中间件
Intro
请求取消
请求取消导致的异常:
request aborted[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 方法中声明 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
来实现自定义的异常处理逻辑,默认请求取消会记录一条 Information 级别的日志,其他异常则会记录一条 Error 级别的错误日志
你可以通过下面的示例来配置遇到请求取消异常的时候什么都不做
service.Configure(options=>
{
options.OnRequestAborted = (context, logger) =>
});