4

I have a couple of custom exceptions in my business layer that bubble up to my API methods in my ASP.NET application.

Currently, they all translate to Http status 500. How do I map these custom exceptions so that I could return different Http status codes?

Sam
  • 26,817
  • 58
  • 206
  • 383

1 Answers1

8

This is possible using Response.StatusCode setter and getter.

Local Exception handling: For local action exception handling, put the following inside the calling code.

var responseCode = Response.StatusCode;
try
{
    // Exception was called
}
catch (BusinessLayerException1)
{
    responseCode = 201
}
catch (BusinessLayerException2)
{
    responseCode = 202
}
Response.StatusCode = responseCode;

For cross controller behavior: You should follow the below procedure.

  1. Create a abstract BaseController
  2. Make your current Controllers inherit from BaseController.
  3. Add the following logic inside BaseController.

BaseController.cs

public abstract class BaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        var responseCode = Response.StatusCode;
        var exception = filterContext.Exception;
        switch (exception.GetType().ToString())
        {
            case "ArgumentNullException":
                responseCode = 601;
                break;

            case "InvalidCastException":
                responseCode = 602;
                break;
        }
        Response.StatusCode = responseCode;
        base.OnException(filterContext);
    }
}

Note:
You can also add the exception as handled and redirecting it into some other Controller/Action

filterContext.ExceptionHandled = true;
filterContext.Result = this.RedirectToAction("Index", "Error");

More Information concerning ASP.NET MVC Error handling can be found HERE

Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • Thank you. This makes sense. One follow up question: where can I put this so that I don't have to repeat this logic in every API method? – Sam Feb 21 '16 at 17:58
  • @Sam, Edited my code, For next time, please state those request at initial post. – Orel Eraki Feb 21 '16 at 18:17