Spring MVC处理异常有3种方式:
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理;
但是方式一仅能获取到异常信息,方式三对已有代码存在入侵性。
实现HandlerExceptionResolver 接口异常处理器
1、增加HandlerExceptionResolver 接口的实现类MyExceptionHandler,代码如下:
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);
}
}
}
- 将Bean添加到Bean工厂,可以在Spring的配置文件applicationContext.xml中增加以下内容
<bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>
或可以使用注解以及扫描添加。
实现定义的异常类即可:
public class BusinessException extends RuntimeException {
/** serialVersionUID */
private static final long serialVersionUID = 2332608236621015980L;
private String code;
public BusinessException() {
super();
}
public BusinessException(String message) {
super(message);
}
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(String code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
public class ParameterException extends RuntimeException {
/** serialVersionUID */
private static final long serialVersionUID = 6417641452178955756L;
public ParameterException() {
super();
}
public ParameterException(String message) {
super(message);
}
public ParameterException(Throwable cause) {
super(cause);
}
public ParameterException(String message, Throwable cause) {
super(message, cause);
}
}
如果我们只相对控制器添加统一的异常捕获程序,最简单的方法就是使用@ControllerAdvice 注解
为控制器添加通知
@ControllerAdvice已经包含了@Component,所以它会自动被组件扫描获取到
@ControllerAdvice
public class AppWideExceptionHandler{
@ExceptionHandler(CommonException.class)
public String commonHandler(){
return "error/commonError";
}
}
重定向异常就是
return "redirect:/error"
``
网友评论