I have an MVC5 project and need to handle exceptions by using a custom method that can be used for all of the Controller or Action methods. For solving the problem I have found some example as posted on Exception handling in ASP.NET MVC and tried to use follow an approach as shown below:
Custom Attribute:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
Controller:
[MyErrorHandler]
public ActionResult Delete(int id)
{
Course deletedCourse = repository.DeleteCourse(id);
if (deletedCourse == null)
{
throw new Exception("Error...");
}
}
View:
$.ajax({
//code omitted for brevity
success: function (result, textStatus, XMLHttpRequest) {
if (!result.success) {
alert(result.error);
}
}
});
Although this approach is working properly, there is not enough information in filterContext to return to the View as an meaningful message or exception type i.e. "database constraint error, etc." So, is there any better approach having a detailed information regarding to exception and using JSON as in this example.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…