springboot專案全域性統一異常處理

2021-10-20 05:41:13 字數 1771 閱讀 7537

在springboot專案開發過程中,不可避免需要處理各種異常,因此各層會出現大量的try catch finally **塊。這樣不僅導致**冗餘,還影響**的可讀性。這樣就需要定義全域性統一異常處理,方便各層呼叫不必單獨捕獲異常。

1.**複製到專案中通過簡單的配置即可實現

2.可以靈活的根據自己的業務異常進行更細粒度的擴充套件

**如下(示例):

public class ajaxresult 

//自定義返回結果的構造方法

public ajaxresult(boolean success,integer code, string msg,object data)

//自定義異常返回的結果

public static ajaxresult defineerror(busines***ception de)

//其他異常處理方法返回的結果

public static ajaxresult othererror(errorenum errorenum)

public boolean getsuccess()

public void setsuccess(boolean success)

public integer getcode()

public void setcode(integer code)

public string getmsg()

public void setmsg(string msg)

public object getdata()

public void setdata(object data)

}

**如下(示例):

public class busines***ception extends runtimeexception 

public busines***ception(integer errorcode, string errormsg)

public integer geterrorcode()

public void seterrorcode(integer errorcode)

public string geterrormsg()

public void seterrormsg(string errormsg)

}

**如下(示例):

public enum errorenum 

public integer geterrorcode()

public string geterrormsg()

}

**如下(示例):

@restcontrolleradvice

public class globalexceptionhandler

/***處理其他異常**/

@exceptionhandler(value = exception.class)

public ajaxresult exceptionhandler( exception e)

}

**如下(示例):

SpringBoot 專案處理全域性異常

springboot 專案處理全域性異常 1.在配置檔案中增加 spring.mvc.throw exception if no handler found true 找不到對應資源丟擲異常 2.新建異常類 controlleradvice public class globalexceptionh...

SpringBoot專案中全域性異常處理

1 引數不滿足條件異常類定義 description 引數不滿足異常處理 author date 2019年8月10日 上午14 17 56 public class promptexception extends runtimeexception public void setcode int c...

聊聊springboot專案全域性異常處理那些事兒

之前我們業務團隊在處理全域性異常時,在每個業務微服務中都加入了 restcontrolleradvice exceptionhandler來進行全域性異常捕獲。某次領導在走查 的時候,就提出了乙個問題,為什麼要每個微服務專案都要自己在寫一套全域性異常 為什麼不把全域性異常塊抽成乙個公共的jar,然後...