1、springboot的默認異常處理spring
Spring Boot提供了一個默認的映射:/error
,當處理中拋出異常以後,會轉到該請求中處理,而且該請求有一個全局的錯誤頁面用來展現異常內容。瀏覽器
例如這裏咱們認爲製造一個異常springboot
@GetMapping(value = "/boys") public List<Boy> boyList() throws Exception{ throw new Exception("錯誤"); }
使用瀏覽器訪問http://127.0.0.1:8080/boysapp
2、自定義的統一異常處理ide
雖然Spring Boot中實現了默認的error映射,可是在實際應用中,上面你的錯誤頁面對用戶來講並不夠友好,咱們一般須要去實現咱們本身的異常提示。工具
1) 統一的異常處理類(com.dechy.handle)this
@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)spa
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)code
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)blog
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); }//... }