一、SpringBoot如何進行全局異常處理
- springboot使用@ControllerAdvice注解進行全局異常處理,并且可以使用@ExceptionHandler注解進行自定義異常處理,如下:
@ControllerAdvice
@ResponseBody
public class GlobleException {
private static Logger log = LoggerFactory.getLogger(GlobleException.class);
@ExceptionHandler(NullPointerException.class)
public JsonResult nullPointHandler(){
log.info("進入到GlobleException中的nullPointHandler方法中");
return new JsonResult("9999","空指針異常");
}
}
- 定義一個controller進行測試,如下:
@RestController
@Api(value="異常資訊測試")
public class ExceptionController {
@GetMapping("/testExcep1")
@ApiOperation(value="空指針異常全局處理測試")
public JsonResult testExcp1(){
Map map = null;
map.put("111",1);
return new JsonResult();
}
}
如上所示,定義一個為null的map對象,在進行put操作的時候就會出現NullPointException,在我們定義的全局處理異常處理類GlobleException中的nullPointHandler中就可以捕獲到這個異常然後進行統一處理。上述中我們用統一定義的JsonResult類來進行封裝處理。
- 啟動springboot工程,調用接口testExcp1,就可以看到響應資訊,并且在控制台列印對應的資訊:
控制台列印資訊如下:
二、自定義異常封裝類,進行異常的處理
- 業務處理過程中有很多類型的異常,是以我們先定義一個BusinessExcpEnum枚舉類,裡面定義各式各樣的異常資訊,後續有新的異常資訊可以統一在這個枚舉類裡面進行維護
public enum BusinessExceptionEnum {
BUSINESS_EXCEPTION("0001","業務異常");
private String code;
private String msg;
BusinessExceptionEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 自定義一個異常類,繼承RuntimeException類,引用上面定義的枚舉類進行異常資訊的提醒:
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = -7480022450501760611L;
private String code;
private String msg;
public BusinessException(BusinessExceptionEnum businessExceptionEnum) {
this.code = businessExceptionEnum.getCode();
this.msg = businessExceptionEnum.getMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 在GlobleException類中定義一個方法用來捕獲上述自定義的異常類,統一進行處理:
@ExceptionHandler(BusinessException.class)
public JsonResult handlerBusinessError(BusinessException e){
log.info("進入到GlobleException中的handlerBusinessError方法中");
return new JsonResult(e.getCode(),e.getMsg());
}
可以看出在@ExceptionHandler中的value為我們自定義的異常處理類,BusinessException
- 在ExceptionController中定義一個方法裡面throw出來一個自定義的異常,提示資訊使用自定義的枚舉中的資訊:
@GetMapping("/testExcp")
@ApiOperation(value="業務異常全局處理測試")
public JsonResult testExcp(){
try{
int i = 1/0;
}catch (Exception e){
throw new BusinessException(BusinessExceptionEnum.BUSINESS_EXCEPTION);
}
return new JsonResult();
}
- 啟動springboot工程,輸入:http://localhost:8080/testExcp,界面上就會展示我們自定義的業務資訊:
控制台列印資訊為: