异常处理程序属性

此属性处理代码中所有未处理的异常(这主要是针对 Ajax 请求 - 处理 JSON - 但可以扩展)

public class ExceptionHandlerAttribute : HandleErrorAttribute
{
    /// <summary>
    ///   Overriden method to handle exception
    /// </summary>
    /// <param name="filterContext"> </param>
    public override void OnException(ExceptionContext filterContext)
    {
        // If exeption is handled - return ( don't do anything)
        if (filterContext.ExceptionHandled)
            return;

        // Set the ExceptionHandled to true ( as you are handling it here)
        filterContext.ExceptionHandled = true;

        //TODO: You can Log exception to database or Log File

        //Set your result structure 
        filterContext.Result = new JsonResult
        {
            Data = new { Success = false, Message = filterContext .Exception.Message, data = new {} },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };

    }
}

所以,假设你总是要发送类似于此的 JSON 响应:

{ 

    Success: true,  // False when Error
    
    data: {},
    
    Message:"Success" // Error Message when Error

}

因此,不要在控制器操作中处理异常,如下所示:

public ActionResult PerformMyAction()
{
    try
    {
        var myData = new { myValue = 1};
        
        throw new Exception("Handled", new Exception("This is an Handled Exception"));
        
        return Json(new {Success = true, data = myData, Message = ""});
    
    }
    catch(Exception ex)
    {
        return Json(new {Success = false, data = null, Message = ex.Message});
    }
}

你可以这样做:

[ExceptionHandler]
public ActionResult PerformMyAction()
{
        var myData = new { myValue = 1};
        
        throw new Exception("Unhandled", new Exception("This is an unhandled Exception"));
        
        return Json(new {Success = true, data = myData, Message = ""});
}

或者你可以在控制器级别添加

[ExceptionHandler]
public class MyTestController : Controller
{
    
    public ActionResult PerformMyAction()
    {
            var myData = new { myValue = 1};
            
            throw new Exception("Unhandled", new Exception("This is an unhandled Exception"));
            
            return Json(new {Success = true, data = myData, Message = ""});
    }
}