Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Exception Handling Web Api 2

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 [email protected] 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?

like image 716
Aeseir Avatar asked May 13 '17 10:05

Aeseir


People also ask

How do I register an exception filter globally in Web API?

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration. Configuration. Filters collection. Exception filters in this collection apply to any Web API controller action.

How do you handle global exception?

In the Design tab part of the Ribbon, select New > Global Handler. The New Global Handler window opens. Type in a Name for the handler and save it in the project path. Click Create, a Global Exception Handler is added to the automation project.

How does Web API handle global exception in .NET core?

The middleware UseExceptionHandler can be used to handle exceptions globally. You can get all the details of the exception object (Stack Trace, Inner exception, message etc..) and display them on-screen. You can implement like this.

How do you handle exceptions in API?

With exception filters, you can customize how your Web API handles several exceptions by writing the exception filter class. Exception filters catch the unhandled exceptions in Web API. When an action method throws an unhandled exception, execution of the filter occurs.


1 Answers

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
like image 75
Samvel Petrosov Avatar answered Sep 23 '22 16:09

Samvel Petrosov