一、springboot的默認異常處理
Spring Boot提供了一個默認的映射:/error,當處理中拋出異常之后,會轉到該請求中處理,並且該請求有一個全局的錯誤頁面用來展示異常內容。
例如這里我們認為制造一個異常
@GetMapping(value = "/boys") public List<Boy> boyList() throws Exception{ throw new Exception("錯誤"); }
使用瀏覽器訪問http://127.0.0.1:8080/boys

二、自定義的統一異常處理
雖然Spring Boot中實現了默認的error映射,但是在實際應用中,上面你的錯誤頁面對用戶來說並不夠友好,我們通常需要去實現我們自己的異常提示。
1) 統一的異常處理類(com.dechy.handle)
@ControllerAdvice public class ExceptionHandle { private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class) @ResponseBody public Result handle(Exception e) { if (e instanceof BoyException) { BoyException boyException = (BoyException) e; return ResultUtil.error(boyException.getCode(), boyException.getMessage()); }else { logger.error("【系統異常】{}", e); return ResultUtil.error(-1, "未知錯誤"); } } }
2)自定義異常類(com.dechy.exception)
public class BoyException extends RuntimeException{ private Integer code; public BoyException(ResultEnum resultEnum) { super(resultEnum.getMsg()); this.code = resultEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
3)返回結果枚舉(com.dechy.enums)
public enum ResultEnum { UNKONW_ERROR(-1, "未知錯誤"), SUCCESS(0, "成功"), TOOSHORT(100, "身高太矮"), TOOHIGH(101, "身高太高"), ; private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } }
4)返回結果工具類(com.dechy.util)
public class ResultUtil { public static Result success(Object object) { Result result = new Result(); result.setCode(0); result.setMsg("成功"); result.setData(object); return result; } public static Result success() { return success(null); } public static Result error(Integer code, String msg) { Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } }
5)Boy實體類(com.dechy.model)
@Entity
public class Boy {
@Id
@GeneratedValue
private Integer id;
@NotBlank(message = "這個字段必傳")
private String height;
@Min(value = 100, message = "體重必須大於100")
private BigDecimal weight;
public Integer getId (){
return id;
}
public void setId (Integer id){
this.id = id;
}
public String getHeight (){
return height;
}
public void setHeight (String height){
this.height = height;
}
public BigDecimal getWeight (){
return weight;
}
public void setWeight (BigDecimal weight){
this.weight = weight;
}
@Override
public String toString (){
return "Boy{" + "id=" + id + ", height='" + height + '\'' + ", weight=" + weight + '}';
}
}
6)業務層具體使用時拋出異常,等待統一處理(com.dechy.service)
public void chooseBoy(Integer id) throws Exception{ Boy boy= boyRepository.findOne(id); Integer height= boy.getHeight(); if (height < 100) { //返回"身高矮" code=100 throw new BoyException(ResultEnum.TOOSHORT); }else if (height > 200) { //返回"身高太高" code=101 throw new BoyException(ResultEnum.TOOHIGH); }//... }
