前言
之前寫過一篇博客是使用spring利用HandlerExceptionResolver實現全局異常捕獲
里面使用spring的HandlerExceptionResolver接口來實現全局的異常捕獲,當時使用,但其實之后已經替換
當前項目中使用的是:@ControllerAdvice 、@ExceptionHandler通過這兩個注解來實現全局的異常捕獲
已經加入我的github模版中:https://github.com/LinkinStars/springBootTemplate
實現
創建GlobalExceptionResolver,實現如下:
import com.linkinstars.springBootTemplate.exception.ServiceException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; /** * 全局異常處理 * @author LinkinStar */ @ControllerAdvice public class GlobalExceptionResolver { @ExceptionHandler(value = ServiceException.class) public @ResponseBody String serviceCommonExceptionHandler(ServiceException e) { //對捕獲的異常進行處理並打印日志等,之后返回json數據,方式與Controller相同 return "{'code':-1}"; } @ExceptionHandler(value = Exception.class) public ModelAndView exceptionHandler() { //當然也可以直接返回ModelAndView等類型,然后跳轉相應的錯誤頁面,這都根據實際的需要進行使用 return new ModelAndView(); } }
其中ServiceException是自定義的異常
/** * 自定義異常 * @author LinkinStar */ public class ServiceException extends RuntimeException{ }
spring會根據ExceptionHandler中的值進行匹配,如果你的一些異常沒有被捕獲,這里就會處理一些你沒有捕獲的異常
至於你需要返回一個頁面還是需要返回一個json數據,這就看實際的業務場景了。
使用原因
在之前的博客中也提出,spring官方推薦這樣的寫法,但當時沒有在意,在實際使用中出現問題后,最終還是采用了這樣的方式,理由主要有下面幾點:
1、使用注解的方式代碼看上去更加的清晰。
2、對於自定義異常的捕獲會很方便。
3、適用於對於返回json格式的情況(可以使用@ResponseBody注解方法對特定異常進行處理),使用HandlerExceptionResolver的話如果是ajax的請求,出現異常就會很尷尬,ajax並不認識ModelAndView。
