一,应用场景:想用于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)
- Exception:在程序中必须使用try...catch进行处理。
- 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