2019-05-06 13:17:22 3453瀏覽
今天千鋒扣丁學堂Java培訓老師給大家分享一篇關于SpringBoot使用統(tǒng)一異常處理詳解,下面我們一起來看一下吧。@Controller
public class HelloController {
private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
@GetMapping(value = "/hello")
@ResponseBody
public Result hello() {
try {
//TODO 具體的邏輯省略……
} catch (Exception e) {
logger.error("hello接口異常={}", e);
return ResultUtil.success(-1, "system error", null);
}
return ResultUtil.success(0, "success", null);
}
}
public class GlobalException extends RuntimeException {
private Integer code; //因為我需要將異常信息也返回給接口中,所以添加code區(qū)分
public GlobalException(Integer code,String message) {
super(message); //把自定義的message傳遞個異常父類
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
@ControllerAdvice
public class ExceptionHandle {
@ResponseBody //因為我需要將拋出的異常返回給接口,所以加上此注解
@ExceptionHandler
public Result handle(Exception e) {
if (e instanceof GlobalException) {
GlobalException ge = (GlobalException) e;
return ResultUtil.success1(ge.getCode(), ge.getMessage());
}
return ResultUtil.success1(-1, "system error!");
}
}
@GetMapping(value = "/hello1")
@ResponseBody
public Result hello(@RequestParam(value = "age", defaultValue = "50", required = false) Integer age) throws GlobalException {
if (age < 10) {
throw new GlobalException(ConstantEnum.LESS10.getCode(), ConstantEnum.LESS10.getMsg());
} else if (age > 50) {
throw new GlobalException(ConstantEnum.MORE50.getCode(), ConstantEnum.MORE50.getMsg());
} else {
return ResultUtil.success1(0, "success");
}
}
public enum ConstantEnum {
ERROR(-1, "system error!"),
SUCCESS(100, "success"),
LESS10(101, "自定義異常信息-我小于10歲"),
MORE50(5001, "自定義異常信息-我大于50歲");
private Integer code;
private String msg;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
ConstantEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
【關注微信公眾號獲取更多學習資料】 【掃碼進入HTML5前端開發(fā)VIP免費公開課】