所有错误统一处理,不论dao层,service层,controller层都层层向向上抛, 具体实现如下
1. spring提供的类SimpleMappingExceptionResolver
2. spring接口HandlerExceptionResolver
3. spring注解ExceptionHandler
具体实现例子
1.1 继承类SimpleMappingExceptionResolver 并初始化相关参数
1.2 在applicationContext.xml 上SimpleMappingExceptionResolver配置对应的bean和相关参数
2.1 实现HandlerExceptionResolver接口
@Component
public class MyExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("ex", ex);
if(ex instanceof BusinessException) {
return new ModelAndView("error-business", model);
}else if(ex instanceof ParameterException) {
return new ModelAndView("error-parameter", model);
} else {
return new ModelAndView("error", model);
}
}
}
3.1 自定义一个基类的业务上加入@ExceptionHandler,内容和2.1相同,其他Controller继承此基类
public class BaseController {
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
request.setAttribute("ex", ex);
if(ex instanceof BusinessException) {
return "error-business";
}else if(ex instanceof ParameterException) {
return "error-parameter";
} else {
return "error";
}
}
}
public class OtherController extends BaseController
来源:oschina
链接:https://my.oschina.net/u/656519/blog/755341