轉載請标明出處:http://blog.csdn.net/zhaoyanjun6/article/details/80678034
本文出自【趙彥軍的部落格】
在用
spring Boot
做
web
背景時,經常會出現異常,如果每個異常都自己去處理很麻煩,是以我們建立一個全局異常處理類來統一處理異常。通過使用
@ControllerAdvice
定義統一的異常處理類,而不是在每個
Controller
中逐個定義。
ControllerAdvice
@ControllerAdvice
,是
Spring3.2
提供的新注解,從名字上可以看出大體意思是控制器增強。
執行個體講解
下面我們通過一個例子,捕獲
IndexOutOfBoundsException
異常,然後統一處理這個異常,并且給使用者傳回統一的響應。
建立異常統一處理類:
ExceptionAdvice
package com.yiba.didiapi.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({ IndexOutOfBoundsException.class })
@ResponseBody
public String handleIndexOutOfBoundsException(Exception e) {
e.printStackTrace();
return "testArrayIndexOutOfBoundsException";
}
}
定義
ApiController
類
@RestController
public class ApiController {
@GetMapping("getUser")
public String getUser() {
List<String> list = new ArrayList<>();
return list.get();
}
}
可以看到在
getUser
方法中, 會抛出
IndexOutOfBoundsException
異常。但是這個異常不會通過接口抛給使用者,會被
ExceptionAdvice
類攔截,下面我們用
postMan
驗證一下。
統一處理自定義異常
自定義
GirlException
異常
public class GirlException extends RuntimeException {
private Integer code;
public GirlException(Integer code, String msg) {
super(msg);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
在
controller
裡面抛出異常,建立
ApiController
@RestController
public class ApiController {
@GetMapping("getUser/{id}")
public String getUser(@PathVariable("id") Integer id) {
if (id == ) {
throw new GirlException(, "年齡太小了");
} else if (id == ) {
throw new GirlException(, "年齡不夠18歲");
}
return "ok";
}
}
自定義統一傳回對象
ResultUtil
public class ResultUtil {
int code;
String mes;
public ResultUtil(int code, String mes) {
this.code = code;
this.mes = mes;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMes() {
return mes;
}
public void setMes(String mes) {
this.mes = mes;
}
}
建立異常統一處理類:
ExceptionAdvice
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({Exception.class})
@ResponseBody
public ResultUtil handleIndexOutOfBoundsException(Exception e) {
ResultUtil resultUtil;
if (e instanceof GirlException) {
GirlException girlException = (GirlException) e;
resultUtil = new ResultUtil(girlException.getCode(), girlException.getMessage());
return resultUtil;
}
return new ResultUtil(, "未知異常");
}
}
測試
個人微信号:zhaoyanjun125 , 歡迎關注