Global Exception Handling Web Api 2
asp.net, asp.net-web-api2, c#
Solution
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
Problem
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?