Skip to content

Instantly share code, notes, and snippets.

@karbyninc
Last active July 4, 2018 10:38
Show Gist options
  • Save karbyninc/2f6e3e5c88805761f89c to your computer and use it in GitHub Desktop.
Save karbyninc/2f6e3e5c88805761f89c to your computer and use it in GitHub Desktop.
Handling Errors in Web API Using Exception Filters and Exception Handlers
public override void OnException(HttpActionExecutedContext actionExecutedContext)
public class DivideByZeroExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception is DivideByZeroException)
{
actionExecutedContext.Response = new HttpResponseMessage()
{ Content = new StringContent("We apologize but an error occured within the application. Please try again later.", System.Text.Encoding.UTF8, "text/plain"), StatusCode = System.Net.HttpStatusCode.InternalServerError};
}
}
}
[DivideByZeroExceptionFilter]
public void Delete(int id)
{
throw new DivideByZeroException();
}
config.Filters.Add(new DivideByZeroExceptionFilter());
//A global exception handler that will be used to catch any error
public class MyExceptionHandler : ExceptionHandler
{
//A basic DTO to return back to the caller with data about the error
private class ErrorInformation
{
public string Message { get; set; }
public DateTime ErrorDate { get; set; }
}
public override void Handle(ExceptionHandlerContext context)
{
//Return a DTO representing what happened
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new ErrorInformation { Message="We apologize but an unexpected error occured. Please try again later.", ErrorDate=DateTime.UtcNow }));
//This is commented out, but could also serve the purpose if you wanted to only return some text directly, rather than JSON that the front end will bind to.
//context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, "We apologize but an unexpected error occured. Please try again later."));
}
}
config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment