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?
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.
- Create a abstract BaseController
- Make your current Controllers inherit from BaseController.
- 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