Could you clarify what is the best practice with Web API error management?

Technology CommunityCategory: ASP.NET Web APICould you clarify what is the best practice with Web API error management?
VietMX Staff asked 3 years ago

Web API provides a great deal of flexibility in terms of exception handling:

  • Use HttpResponseException or the shortcut methods to deal with unhandled exceptions at the action level.
[Route("CheckId/{id}")]
[HttpGet]
public IHttpActionResult CheckId(int id)
{
    if (id > 100)
    {
        var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("We cannot use IDs greater than 100.")
        };
        throw new HttpResponseException(message);
    }
    return Ok(id);
}
  • Use Exception Filters to deal with particular unhandled exceptions on multiple actions and controllers.
[Route("ItemNotFound/{id}")]
[HttpPost]
[ItemNotFoundExceptionFilter] // Exception filter
public IHttpActionResult ItemNotFound(int id)
{
    _service.ThrowItemNotFoundException();
    return Ok();
}
  • Use ExceptionLogger to log any unhandled exception.
public class UnhandledExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        var log = context.Exception.ToString();
        //Do whatever logging you need to do here.
    }
}
  • Use Exception Handlers (one per application) to deal with any unhandled exception application-wide. They called after Exception Filters and Exception Loggers.