How can one log all Internal Server Error 500 errors returned by all actions in Web Api 2? How do you intercept the error to be able to log the Stack Trace ?
Today there's no easy way in Web API to log or handle errors globally. Some unhandled exceptions can be processed via exception filters, but there are a number of cases that exception filters can't handle. For example: Exceptions thrown from controller constructors.
Symptom. The client application gets an HTTP status code of 500 with the message Internal Server Error as a response for API calls. The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from fulfilling the request.
The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. This error response is a generic "catch-all" response.
I just wanted to keep it simple and make sure I logged the exception.
Create an ExceptionFilter class like below
public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
// actionExcutedContext.Exception is the exception log it however you wish
Log.Exception(actionExecutedContext.Exception);
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, new
{
actionExecutedContext.Exception.Message
});
}
}
You also must configure WebAPI to call the filter. This is done when you create your configuration.
config.Filters.Add(new ExceptionFilter());
The Log.Exception
line is just a helper class for me, you can log it however you choose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With