Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom exceptions to Http status codes in ASP.NET API

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?

like image 375
Sam Avatar asked Feb 08 '23 16:02

Sam


1 Answers

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

like image 119
Orel Eraki Avatar answered Feb 16 '23 02:02

Orel Eraki