使用@ControllerAdvice注解,將Controller中未使用try-catch捕獲異常的踪古,進(jìn)行統(tǒng)一處理祖灰,
建立GlobalExceptionHandler類使用@ControllerAdvice注解
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String,Object> handlerException(){
Map<String,Object> map = new HashMap<>();
map.put("code",500);
map.put("msg","系統(tǒng)繁忙钟沛,請稍后重試");
return map;
}
@ExceptionHandler(BusinessException.class)
@ResponseBody
public Map<String,Object> handlerBusinessException(BusinessException businessException){
Map<String,Object> map = new HashMap<>();
map.put("code",businessException.getCode());
map.put("msg",businessException.getMsg());
map.put("desc",businessException.getDesc());
return map;
}
@ExceptionHandler(SQLException.class)
@ResponseBody
public Map<String,Object> handlerSQLException(){
Map<String,Object> map = new HashMap<>();
return map;
}
}
其中BusinessException是業(yè)務(wù)定制異常,在使用過程中可以直接拋出異常局扶。如下:
@RequestMapping("/home2")
@ResponseBody
String getProductData2() throws BusinessException {
throw new BusinessException(500,"系統(tǒng)異常","系統(tǒng)走神了");
}
下邊是業(yè)務(wù)異常定制的實體恨统,可根據(jù)業(yè)務(wù)需求定制:
/**
* 業(yè)務(wù)異常
*/
public class BusinessException extends Exception{
/*異常處理編碼*/
private Integer code;
/*異常處理信息*/
private String msg;
/*異常處理描述*/
private String desc;
public BusinessException(Integer code, String msg, String desc) {
this.code = code;
this.msg = msg;
this.desc = desc;
}
public BusinessException(String msg) {
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}