前端返回错误码的注解
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户不匹配" )
public class GyExceptionThree extends RuntimeException {
private static final long serialVersionUID = 1L;
}
抛出注解的异常
@RequestMapping(value="exception")
public String ecxeption(HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse ,User user) throws Exception {
if(user.getUserName()==null) {
System.out.println("用户名不能为空1");
throw new GyExceptionThree();
}
return "custom_error";
}
问题:当利用@ResponseStatus注解 在全局异常处理中用了@ControllerAdvice,就会出现异常被全局异常处理类捕获不会再页面显示相应的错误状态码。
如果仅仅是想处理状态码异常 可以在全局异常处理的类中加以判断然后抛出异常。
@ControllerAdvice
public class BaseExceptionController {
@ExceptionHandler(value=Exception.class)
public ModelAndView resolveException(Exception ex) throws Exception {
if(AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class)!=null) {
throw ex;
}
ModelAndView mv = new ModelAndView();
System.out.println("diao yong de shi me ");
mv.setViewName("custom_error");
if (ex instanceof GyException) {
ex = (GyException)ex;
mv.addObject("message", ex.getMessage());
System.out.println("i am com in 2");
mv.setViewName("custom_error");
} else if (ex instanceof RuntimeException) {
System.out.println("i am com in 3");
mv.setViewName("custom_error");
}
return mv;
}
}