Need a complete sample to handle unhandled exceptions using "ExceptionHandler" in ASP.NET Web Api?
asp.net-web-api, c#, exception
Solution
In your WebApi config your need to add the line:
config.Services.Replace(typeof (IExceptionHandler), new OopsExceptionHandler());
Also make sure you have created the base ExceptionHandler class that implements IExceptionHandler:
public class ExceptionHandler : IExceptionHandler
{
public virtual Task HandleAsync(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
if (!ShouldHandle(context))
{
return Task.FromResult(0);
}
return HandleAsyncCore(context, cancellationToken);
}
public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
HandleCore(context);
return Task.FromResult(0);
}
public virtual void HandleCore(ExceptionHandlerContext context)
{
}
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return context.CatchBlock.IsTopLevel;
}
}
Note that this will only deal with exceptions that are not handled elsewhere (e.g. by Exception filters).
Problem
I had checked this link http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling. In this link they mentioned like this ``` class OopsExceptionHandler : ExceptionHandler { public override void HandleCore(ExceptionHandlerContext context) { context.Result = new TextPlainErrorResult { Request = context.ExceptionContext.Request, Content = "Oops! Sorry! Something went wrong." + "Please contact support@contoso.com so we can try to fix it." }; } private class TextPlainErrorResult : IHttpActionResult { public HttpRequestMessage Request { get; set; } public string Content { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError); response.Content = new StringContent(Content); response.RequestMessage = Request; return Task.FromResult(response); } } } ``` I don't know how to call this class in my Web API actions. So can any one give me the complete sample using this `ExceptionHandler`.