異常處理程式屬性

此屬性處理程式碼中所有未處理的異常(這主要是針對 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 = ""});
    }
}