關於異常,參見:
Java異常
沒有異常處理
controller中測試類:
@GetMapping("/testException")
public Integer testException(Integer a,Integer b) {
return a+b;
}
測試:
如果參數a和b中有一個爲空,則會報空指針異常:
瀏覽器頁面長這樣:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-tMWuB6qr-1590583383167)(http://img.liuyj.top/統一異常處理-3.jpg)]
全局統一異常處理
添加全局統一異常處理類:
package com.example.conf;
import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseStatus;
/**
* @author liuyj
* @Title: ControllerHandler 自定義處理異常
* @create 2020-05-14 10:45
* @ProjectName test
* @Description: TODO
*/
@ControllerAdvice
public class ControllerHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResultInfo handleException(Exception ex){
System.out.println("程序異常:"+ex.toString());
return new ResultInfo(5000,"請求失敗");
}
}
再次測試:
自定義異常處理
添加異常UserNotExistException類:
public class UserNotExistException extends Exception{
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UserNotExistException(Integer id){
this.id=id;
}
@Override
public String toString() {
return "用戶不存在";
}
}
controller拋出異常:
@PostMapping("/getUser")
public boolean getUser() throws UserNotExistException {
throw new UserNotExistException(10);
}
先測試,我們只是拋出異常,並沒有對異常進行處理:
添加異常處理:
package com.example.conf;
import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseStatus;
/**
* @author liuyj
* @Title: ControllerHandler 自定義處理異常
* @create 2020-05-14 10:45
* @ProjectName test
* @Description: TODO
*/
@ControllerAdvice
public class ControllerHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResultInfo handleException(Exception ex){
System.out.println("程序異常:"+ex.toString());
return new ResultInfo(5000,"請求失敗");
}
/**
* 處理UserNotExistException異常
*/
@ExceptionHandler({UserNotExistException.class})
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResultInfo handleUserNotExistException(UserNotExistException ex) {
System.out.println("請求用戶數據異常:" + ex.toString());
return new ResultInfo(5000, "請求用戶數據失敗");
}
}
測試:
可以看到已經處理。
測試之前的空指針異常,也沒問題
被要求單獨處理的異常會先被處理,而後其他異常會被Exception(默認形式)的處理方法捕獲。