OnException - twice call
.net, asp.net-mvc
Solution
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! :)
Problem
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?