Reputation: 8236
I need a way to handle and log all exceptions occuring in web api in one place. I override the methods of both ExceptionLogger and ExceptionHandler, but the code breaks and never triggers the handling mechanisms.
If I changed my controller to have to same API Methods, which cause another error:
[RoutePrefix("api/Ads")]
public class AdsController : ApiController
{
public IHttpActionResult Get()
{
return Ok(Ad.GetAds());
}
public IHttpActionResult Get(object name)
{
return Ok();
}
}
The handler is going to catch the error:
In this case the error is :
Multiple actions were found that match the request:
Are the ExceptionLogger and ExceptionHandler catching only errors caused by web api at higher level? and what should i do to handle all errors, are Exception Filters the solution which have to be added also?
Upvotes: 0
Views: 2226
Reputation: 8236
The ExceptionLogger and Filter was not catching any errors since the project was in debug mode, In debug mode it throws the exception and stop there, while in release mode the exception is caught by logger or filters.
Upvotes: 0
Reputation: 16502
Add an Exception filter:
public class MyExceptionFilter:ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var t = HandleException(context);
t.Wait();
}
public override async Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
{
await HandleException(context);
}
private Task HandleException(HttpActionExecutedContext context)
{
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception.Message);
return Task.CompletedTask;
}
}
Then in your WebApiConfig.Register
method add this line:
config.Filters.Add(new MyExceptionFilter());
Upvotes: 2