Springboot處理全域性異常並自動獲取狀態碼
阿新 • • 發佈:2020-12-20
技術標籤:程式碼
傳送請求後,一旦出現異常,系統自動捕獲
狀態碼由response.getStatus()方法獲取
/**
* 異常處理類
*
*/
@RestControllerAdvice
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
ExceptionMessage HandlerException(Exception e,HttpServletResponse response) {
int code = response.getStatus();
return new ExceptionMessage(code, "服務端錯誤");
}
}
public class ExceptionMessage {
private int code;
private String message;
public ExceptionMessage(int code, String message) {
super();
this.code = code;
this.message = message;
}
public int getCode () {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}