上一节我们介绍了如何使用 注解来标记需要校验,配合@Valid 进行
但是 如果校验住了那么 会抛出 org.springframework.validation.BindException
这个时候还没到我们的controller的方法执行呢
因此我们需要进行一场的拦截
异常拦截机制
异常的拦截本质就是aop的使用了
我们对于拦截器的使用 定义切面,advice , 以及切点
这里异常的拦截的切点就是 抛出的异常
advice就是出现异常之后我们如何处理
需要使用 下面的这个注解
@ControllerAdvice 标记这个类是一个切面的advice类
然后配合
@ExceptionHandler 指定处理方法
(这套东西 在以前是在 过滤器中进行操作的)
例如下面的例子:
package miaosha.exception;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import miaosha.result.Result;
/**
* 异常拦截器
* @author kaifeng1
*
*/
@ControllerAdvice
@ResponseBody
public class AppliCationExceptionHandler {
@ExceptionHandler(value=Exception.class)
public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
e.printStackTrace();
if(e instanceof ApplicationException) {
ApplicationException ex = (ApplicationException)e;
return Result.error(ex.getErrorCode()+":"+ex.getMsg());
}else if(e instanceof BindException) {
BindException ex = (BindException)e;
List<ObjectError> errors = ex.getAllErrors();
ObjectError error = errors.get(0);
String msg = error.getDefaultMessage();
return Result.errorArgs(msg, errors);
}
return Result.error(e.getMessage()) ;
}
}
在调用controller的时候
如果发现参数中有 @Valid 进行的修饰,就会进行校验了
我们回顾下之前的写的注解
这里的 String message() default "手机号码格式错误";
将来被校验住就是下面的异常拦截器的第一个 error