1、概述
Spring Boot 处理异常的两种方式:
1) @ControllerAdvice + @ExceptionHandler:配置对全局异常进行处理
2) @Controller + @ExceptionHandler:配置对当前所在Controller的异常进行处理
2、实战
2.1、@ControllerAdvice + @ExceptionHandler:配置对全局异常进行处理
创建需要定义的异常, 或者是使用java自带
public class ZkOperationException extends RuntimeException {
private static final long serialVersionUID = 4708512975487042443L;
private Integer code;
private String msg;
public ZkOperationException(String message){
super(message);
this.msg = message;
}
public ZkOperationException(PromptMessageCode code){
super(code.toString());
this.code = code.getCode();
this.msg = code.getMsg();
}
public ZkOperationException(PromptMessageCode code, Throwable cause) {
super(code.toString(), cause);
this.code = code.getCode();
this.msg = code.getMsg();
}
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;
}
}
定义异常处理类
@ControllerAdvice
public class GlobalExceptionHandler extends BaseResponse{
@ExceptionHandler(value = ZkOperationException.class)
@ResponseBody
public CommonResponse jsonErrorHandler(HttpServletRequest req, ZkOperationException e){
return getResultFailure(null, e.getMsg());
}
}
当在调用的地方, 出错后抛出ZkOperationException 这个异常, 进行处理, 当然如果有多种类型可以, 直接使用Exception。
2.2 @Controller + @ExceptionHandler:配置对当前所在Controller的异常进行处理
创建controller
@Controller
@RequestMapping("userAndZkBind")
public class UserAndZkBindController extends BaseController {
@Autowired
private ZkInfoService zkInfoService;
@RequestMapping(value = "/applyZkConnectionInfo", method = RequestMethod.POST)
@ResponseBody
public CommonResponse<ZkConnectionInfo> applyZkConnectionInfo(){
// 这里是业务内容不写。
return null;
}
@ExceptionHandler(ZkOperationException.class)
public CommonResponse HandlerErrorJson(HttpServletRequest request, Exception ex){
return getResultFailure(null, ex.getMessage());
}
}
3、总结
两种方法都可以对异常进行处理, 返回预定义的提示信息。
读者可以根据实际情况, 进行相应的操作