Global Exception Handling Web Api 2

Viewed 6754

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://docs.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?

2 Answers
Related