LINQ2Vodka
LINQ2Vodka

Reputation: 3036

OnException - twice call

I have BaseController class with OnException handler.

public class ApiBaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.Result = ...
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        filterContext.ExceptionHandled = true;
    }
}

My inherited controllers have custom HandleJsonError on their actions:

public class ApiCompanyController : ApiBaseController
{
    [HttpPost, HandleJsonError]
    public ActionResult Delete(int id)
    {
        // ...
        if (...) throw new DependentEntitiesExistException(dependentEntities);
        // ...
    }
}

HandleJsonError is:

public class HandleJsonError : HandleErrorAttribute
{
    public override void OnException(ExceptionContext exceptionContext)
    {
        // ...
        exceptionContext.ExceptionHandled = true;
    }
}

When DependentEntitiesExistException exception is risen, both base controller's and HandleJsonError's OnException handlers are called. How can I make not call base controller OnException after HandleJsonError's OnException finished?

Upvotes: 3

Views: 756

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 34992

Check on your base controller if the exception has already been handled. If so, skip the method execution:

public class ApiBaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        //Do not continue if exception already handled
        if (filterContext.ExceptionHandled) return;

        //Error handling logic
        filterContext.Result = ...
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        filterContext.ExceptionHandled = true;
    }
}

PS. Happy new year! :)

Upvotes: 5

Related Questions