SpringMVC统一异常处理

一,应用场景:想用于json返回统一格式化,但是如果每次返回json给前端的时候都要做异常处理,并且每次都要做异常信息处理就特别不方便。,所以怎么统一把我们想要处理的异常管理起来呢?就用到了统一异常处理。

二,异常处理通常有:
1,try-catch处理 通过try捕获异常到catch进行处理。
2,自定异常处理 通过throw抛出异常

三,统一异常处理思路:将异常抛出,我们的例子中模拟了action,service,dao三个层次。怎么把异常统一捕获处理了呢?


三,具体操作:

1,编写三个层次的类
action
@Controller
public class DemoAction {
	@Autowired
	private DemoServiceImp demoServiceImp;
	
	public DemoAction() {
		// TODO Auto-generated constructor stub
	}
	@RequestMapping("demoAction")
	public String demoAction(Integer statu) throws Exception{
		System.out.println("调用action");
		if(statu==4){
			throw new defautException();
		}
		demoServiceImp.service(statu);
		return "success";
	}
}

模拟service
public class DemoServiceImp {
	@Autowired
	private DemoDaoImp demoDaoImp;
	
	public void service(Integer statu) throws Exception{
		System.out.println("这里调用了service");
		if(statu==3){
			throw new defautException();
		}
		demoDaoImp.Dao(statu);
	}
}



模拟dao
public class DemoDaoImp {
	public DemoDaoImp() {
		// TODO Auto-generated constructor stub
	}
	public void Dao(Integer statu)throws Exception{
		System.out.println("这里调用了Dao");
		if(statu==0){
			System.out.println("抛出异常404");
			throw new defautException();
		}else if(statu==1){
			System.out.println("抛出异常500");
			throw new ErrorException();
		}
		System.out.println("dao调用成功");
	}
}



2,编写自定义异常(注意这个自定义异常要实现RuntimeException)
  1. Exception:在程序中必须使用try...catch进行处理。
  2. RuntimeException:可以不使用try...catch进行处理,但是如果有异常产生,则异常将由JVM进行处理。
public class ErrorException extends RuntimeException{
	public ErrorException() {
		super("[error exception]");
	}
}
public class defautException extends RuntimeException{
	public defautException() {
		super("[404 demo exception]");
	}
}



3,编写HandlerException捕获异常
public class HandleException implements HandlerExceptionResolver{
	static Logger logger = Logger.getLogger(HandleException.class);
	public ModelAndView resolveException(HttpServletRequest req,
			HttpServletResponse res, Object handle, Exception ex) {
		String message = ex.getMessage();
		ModelAndView m = new ModelAndView();
		if(ex instanceof defautException){
			System.out.println("跳转404页面");
			logger.error("发现异常 message:{}");
			m.setViewName("404");
		}else if(ex instanceof ErrorException){
			System.out.println("跳转500页面");
			m.setViewName("500");
		}
		return m;
	}

}

4.把bean交给Spring管理



五,测试说明:
为了测试是否起到统一异常处理的作用,我们分别在action,service,dao都加了statu进行拦截判断进行处理。看他是否到Handle处理。

六,测试结果:
statu:1

statu:2


statu:3




















  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值