I have my exception hander:
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
{ ...
How do I use the ILogger in the exception handler? If I make a constructor:
public ApplicationExceptionHandler(ILogger<ApplicationExceptionHandler> logger)
{
this.logger = logger;
}
In my controller I receive an compiler exception:
[ApplicationExceptionHandler (ILogger < ApplicationExceptionHandler > logger)]
Logger is a type which is not valid in this context. How do you add a ILogger to an exception handler?
Ok the syntax on the controller attribute:
[TypeFilter(typeof(ApplicationExceptionHandler))]
And the Exception handler:
public class ApplicationExceptionHandler :ExceptionFilterAttribute
{
private readonly ILogger<ApplicationExceptionHandler> logger;
public ApplicationExceptionHandler(ILogger<ApplicationExceptionHandler> logger)
{
this.logger = logger;
}