Simon
Simon

Reputation: 1476

Web API generic error handling

Using MVC API, If we throw an error within our API controller

public HttpResponseMessage GetError(int id)
    {
            int number1 = 3000;
            int number2 = 0;

            var t = number1 / number2;

    }

we would like to capture this error within our deligatingHandler

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
 message = base.SendAsync(request, cancellationToken);
 if (!message.Result.IsSuccessStatusCode)
            {
              Log.Error(xxxxxxx)
             }
}

Checking all of the properties of the message, it only shows a generic error message and not the error that is thrown by the controller..

Log.Error(xxxxX)

is our call to log4net.

Is there a way to pass this error to the handler? or is there a better way to achieve this?

Upvotes: 1

Views: 1536

Answers (1)

Sergey
Sergey

Reputation: 191

It is better to use generic error attribute filter like below:

 public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {

// log your error here 
           Log.Error(context.Exception);

            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("An error occurred, please try again or contact the administrator."),
                ReasonPhrase = "Critical Exception"
            });
        }

and register it in your WebApiConfig class like:

config.Filters.Add(new ExceptionHandlingAttribute());

Upvotes: 2

Related Questions