愛上MVC~業務層刻意拋出異常,全局異常的捕獲它並按格式返回


回到目錄

對於業務層的程序的致命錯誤,我們一直的做法就是直接拋出指定的異常,讓程序去終斷,這種做法是對的,因為如果一個業務出現了致命的阻塞的問題,就沒有必要再向上一層一層的返回了,但這時有個問題,直接拋異常,意味着服務器直接500了,前端如何去顯示,或者如果你是API的服務,如果為前端返回,如果是500,那直接就掛了,哈哈!

下面是在MVC環境下優化的全局異常捕獲代碼(非API)

    /// <summary>
    /// 全局異常捕獲
    /// </summary>
    public class GlobalExceptionFilterAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            JsonResult response = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            if (context.Exception is ArgumentException)
            {
                var exception = (ArgumentException)context.Exception;
                response.Data = new
                {
                    statusCode = System.Net.HttpStatusCode.InternalServerError,
                    errorcode = "02",
                    message = exception.Message,
                };
            }
            else if (context.Exception is Exception)
            {
                var exception = (Exception)context.Exception;
                response.Data = new
                {
                    statusCode = System.Net.HttpStatusCode.InternalServerError,
                    errorcode = "01",
                    message = exception.Message,
                };
            }
            else
            {

                response.Data = new
                {
                    statusCode = System.Net.HttpStatusCode.InternalServerError,
                    errorcode = "03",
                    message = "其它異常",
                };
            }

            context.Result = response;
            context.ExceptionHandled = true;
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.TrySkipIisCustomErrors = true;
        }


    }

如果業務層有問題,直接就throw了

   if (id == 0)
        throw new ArgumentException("id不能為0");
   if (id < 0)
        throw new ArgumentException("id不能是負數");

然后頁面后,故意讓它拋出異常,我們看一下頁面響應的結果

事實上,對於服務器來說,它是200,正常返回的,而對不業務模塊來說,它的狀態是個500,呵呵,這點要清楚.

感謝各位閱讀!

回到目錄

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM