Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log 500 Errors in WebApi 2

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 ?

like image 999
Sam Leach Avatar asked Feb 03 '15 16:02

Sam Leach


People also ask

How do I log errors in Web API?

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.

What does 500 mean in API?

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.

What is a 500 error code?

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.


1 Answers

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.

like image 163
David Basarab Avatar answered Nov 15 '22 12:11

David Basarab