SpringBoot 是如何統(tǒng)一處理全局異常的滨攻。SpringBoot 中的全局異常處理主要起作用的兩個(gè)注解是 @ControllerAdvice 和 @ExceptionHandler 够话,其中 @ControllerAdvice 是組件注解,添加了這個(gè)注解的類能夠攔截 Controller 的請(qǐng)求光绕,而 ExceptionHandler 注解可以設(shè)置全局處理控制里的異常類型來(lái)攔截要處理的異常女嘲。 比如:@ExceptionHandler(value = NullPointException.class) 。
返回的消息類
public class Message<T> implements Serializable {
/**
* 狀態(tài)碼
*/
private Integer code;
/**
* 返回信息
*/
private String message;
/**
* 返回的數(shù)據(jù)類
*/
private T data;
/**
* 時(shí)間
*/
private Long time;
// getter诞帐、setter 以及 構(gòu)造方法略欣尼。。。
}
工具類
用于處理返回的數(shù)據(jù)以及信息類愕鼓,代碼注釋很詳細(xì)不說(shuō)了钙态。
public class MessageUtil {
/**
* 成功并返回?cái)?shù)據(jù)實(shí)體類
* @param o
* @param <E>
* @return
*/
public static <E>Message<E> ok(E o){
return new Message<>(200, "success", o, new Date().getTime());
}
/**
* 成功,但無(wú)數(shù)據(jù)實(shí)體類返回
* @return
*/
public static <E>Message<E> ok(){
return new Message<>(200, "success", null, new Date().getTime());
}
/**
* 失敗菇晃,有自定義異常返回
* @param code
* @param msg
* @return
*/
public static <E>Message<E> error(Integer code,String msg){
return new Message<>(code, msg, null, new Date().getTime());
}
}
自定義異常
通過(guò)繼承 RuntimeException 册倒,聲明 code 用于定義不同類型的自定義異常。主要是用于異常攔截出獲取 code 并將 code 設(shè)置到消息類中返回磺送。
public class CustomException extends RuntimeException{
/**
* 狀態(tài)碼
*/
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public CustomException(Integer code, String message){
super(message);
this.code = code;
}
}
異常攔截類
通過(guò)加入 @RestControllerAdvice 來(lái)聲明該類可攔截 Controller 請(qǐng)求驻子,同時(shí)在 handle方法加入 @ExceptionHandler 并在該注解中指定要攔截的異常類。
@RestControllerAdvice // 控制器增強(qiáng)處理(返回 JSON 格式數(shù)據(jù))估灿,添加了這個(gè)注解的類能被 classpath 掃描自動(dòng)發(fā)現(xiàn)
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class) // 捕獲 Controller 中拋出的指定類型的異常崇呵,也可以指定其他異常
public <E>Message<E> handler(Exception exception){
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else {
return MessageUtil.error(120, "異常信息:" + exception.getMessage());
}
}
}
這里只對(duì)自定義異常以及未知異常進(jìn)行處理,如果你在某方法中明確知道可能會(huì)拋出某個(gè)異常馅袁,可以加多一個(gè)特定的處理演熟。比如說(shuō)你明確知道該方法可能拋出 NullPointException 可以追加 NullPointException 的處理:
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else if (exception instanceof NullPointException ){
return MessageUtil.error(500, "空指針異常信!");
} else {
return MessageUtil.error(120, "異常信息:" + exception.getMessage());
}
controller 層
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/{id}")
public Message<Student> findStudentById(@PathVariable("id") Integer id){
if (id < 0){
//測(cè)試自定義錯(cuò)誤
throw new CustomException(110, "參數(shù)不能是負(fù)數(shù)司顿!");
} else if (id == 0){
//硬編碼芒粹,為了測(cè)試
Integer i = 1/id;
return null;
} else {
Student student = studentService.findStudentById(id);
return MessageUtil.ok(student);
}
}
}