我有我的例外处理程序:
public class ApplicationExceptionHandler :ExceptionFilterAttribute
{
public ApplicationExceptionHandler()
{
}
public override void OnException(ExceptionContext context)
{
ApiError apiError = null;
switch (context.Exception)
{
case TaxiNotFoundException:
apiError = new ApiError(context.Exception.Message);
context.Result = new ObjectResult(apiError) {StatusCode = StatusCodes.Status404NotFound };
break;
default:
context.Result = new BadRequestResult();
break;
}
base.OnException(context);
}
}
public class ApiError
{
public string Message { get; set; }
public ApiError(string message)
{
Message = message;
}
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
[ApplicationExceptionHandler]
public class TaxisController : ControllerBase
{ ...
如何在异常处理程序中使用ILogger?如果我制作一个构造函数:
public ApplicationExceptionHandler(ILogger<ApplicationExceptionHandler> logger)
{
this.logger = logger;
}
在我的控制器中,我收到编译器异常:
[ApplicationExceptionHandler (ILogger < ApplicationExceptionHandler > logger)]
Logger 是一种在此上下文中无效的类型。如何将 ILogger 添加到异常处理程序?
确定控制器属性的语法:
[TypeFilter(typeof(ApplicationExceptionHandler))]
以及异常处理程序:
public class ApplicationExceptionHandler :ExceptionFilterAttribute
{
private readonly ILogger<ApplicationExceptionHandler> logger;
public ApplicationExceptionHandler(ILogger<ApplicationExceptionHandler> logger)
{
this.logger = logger;
}