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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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, Edited my code, For next time, please state those request at initial post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.