自定义一个异常类,继承RuntimeException
@Getter
public class ErrorInfoException extends RuntimeException {
private String message;
public ErrorInfoException(String message) {
this.message = message;
}
}
异常的全局处理
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 请求方式不支持
*/
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
public AjaxResult handleException(HttpRequestMethodNotSupportedException e) {
log.error(e.getMessage(), e);
return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
}
/**
* 效验提示异常
*/
@ExceptionHandler(ErrorInfoException.class)
public AjaxResult errorInfoException(ErrorInfoException e) {
log.error(e.getMessage(), e);
return AjaxResult.error(e.getMessage());
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public AjaxResult notFount(RuntimeException e) {
log.error("运行时异常:", e);
return AjaxResult.error("运行时异常:" + e.getMessage());
}
/**
* 方法参数效验
*/
@ExceptionHandler(BindException.class)
public AjaxResult bindException(BindException be) {
log.error(be.getMessage(), be);
List<ObjectError> allErrors = be.getBindingResult().getAllErrors();
if (allErrors != null && !allErrors.isEmpty()) {
ObjectError objectError = allErrors.get(0);
return AjaxResult.error(objectError.getDefaultMessage());
}
return AjaxResult.error("效验异常,请联系管理员");
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e) {
log.error(e.getMessage(), e);
return AjaxResult.error("服务器错误,请联系管理员");
}
}
抛出自定义异常ErrorInfoException,给全局处理
@PostMapping("/forget/mobile")
@ResponseBody
public AjaxResult ajaxForget(@Valid ForgetMobileVO vo) {
if (!vo.getPassword().equals(vo.getConfirmPassword())) {
throw new ErrorInfoException("两次密码不一致");
}
return success();
}
参数效验抛出异常BindException
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* 忘记密码 手机校验
*/
@Data
public class ForgetMobileVO {
@NotBlank(message = "手机号不能为空")
private String mobile;
@NotBlank(message = "区号不能为空")
private String mzone;
@NotBlank(message = "验证码不能为空")
private String verifyCode;
@NotBlank(message = "密码不能为空")
private String password;
@NotBlank(message = "确认密码不能为空")
private String confirmPassword;
}