针对错误异常,你可以定义不同的项目自定义异常,类似AOP校验异常,Token校验异常,项目全局异常等
通过Handler进行捕获,并返回对应格式要求的数据,
如下代码 我定义了一个全局、一个校验异常
@Getter
public class SbException extends RuntimeException {
private Integer code;
public SbException(ResultEnum resultEnum){
super(resultEnum.getMessage());
this.code = resultEnum.getCode();
}
public SbException(Integer code, String message){
super(message);
this.code = code;
}
}
public class SbAuthorizeException extends RuntimeException {
}
接着定义handler
@ControllerAdvice
public class SbExceptionHandler {
@Autowired
private ProjectUrlConfig projectUrlConfig;
//拦截登录异常
@ExceptionHandler(value = SbAuthorizeException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public ModelAndView handlerAuthorizeException(){
return new ModelAndView("redirect:"
.concat(projectUrlConfig.getWechatOpenAuthorize())
.concat("/sb/wechat/qrAuthorize")
.concat("?returnUrl=")
.concat(projectUrlConfig.getSb())
.concat("/sb/seller/login"));
}
//全局异常
@ExceptionHandler(value = SbException.class)
@ResponseBody
public ResultVO handlerSbException(SbException e){
return ResultVOUtil.error(e.getCode(),e.getMessage());
}
// Http状态码异常返回
@ExceptionHandler(value = ResponseBankException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)//403
public void handleResponseBankException(){
}
//未知系统异常
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultVO handlerException(Exception e){
return ResultVOUtil.error(666,e.getMessage());
}
}
这样你只需要在对应的地方或业务执行错误时抛出对应的异常即可