springMVC异常处理(4)

前端返回错误码的注解

@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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值