6

I am trying to figure out how to implement a Global Exception Handler in .NET Web Api 2.

I tried following the example set out by Microsoft here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling

But when exception occured, it did nothing.

This is my code:

public class GlobalExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            Trace.WriteLine(context.Exception.Message);

            context.Result = new TextPlainErrorResult
            {
                Request = context.ExceptionContext.Request,
                Content = "Oops! Sorry! Something went wrong." +
                          "Please contact support@testme.com so we can try to fix it."
            };
        }

        private class TextPlainErrorResult : IHttpActionResult
        {
            public HttpRequestMessage Request { private get; set; }

            public string Content { private get; set; }

            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                var response =
                    new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(Content),
                        RequestMessage = Request
                    };
                return Task.FromResult(response);
            }
        }
    }

Is there a better way (or more proper way) to implement a global exception handler?

Aeseir
  • 7,754
  • 10
  • 58
  • 107
  • 1
    If it is not working in your case, you can implement [Exception Filters](http://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/) to handle exception. – mmushtaq May 13 '17 at 10:33
  • _"...better way (or more proper way)...."_ is subject to opinion and sadly off-topic for SO. [ask] –  May 13 '17 at 10:35

2 Answers2

3

Try adding this to your WebApiConfig

webConfiguration.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler()); // You have to use Replace() because only one handler is supported

webConfiguration.Services.Add(typeof(IExceptionLogger), new MyExceptionLogger()); // webConfiguration is an instance of System.Web.Http.HttpConfiguration
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
0

You missed

class GlobalExceptionHandler : ExceptionHandler
{
    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;
    }
    //...
}

See WebApi v2 ExceptionHandler not called

GibbOne
  • 629
  • 6
  • 10