1. 程式人生 > >業務層刻意拋出異常,全局異常的捕獲它並按格式返回

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

ges pub .cn public oba src lob system server

對於業務層的程序的致命錯誤,我們一直的做法就是直接拋出指定的異常,讓程序去終斷,這種做法是對的,因為如果一個業務出現了致命的阻塞的問題,就沒有必要再向上一層一層的返回了,但這時有個問題,直接拋異常,意味著服務器直接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,呵呵,這點要清楚.

感謝各位閱讀!

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