1

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?

1
  • 1
    If you just want to do something with the exception, your best bet is probably a custom Exception Filter. Commented Feb 20, 2017 at 11:37

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.