springmvc异常处理

1、分析 

 

(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver; 

 

(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器; 

(3)使用@ExceptionHandler注解实现异常处理;

2 实例

  2.1、异常类定义 

 

/**  
 * 系统业务异常  
 */    
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);    
    }    
}  

 

 

 

  2.2 Dao层代码 

 

@Repository("testDao")  
public class TestDao {  
    public void exception(Integer id) throws Exception {  
        switch(id) {  
        case 1:  
            throw new BusinessException("12", "dao12");  
        case 2:  
            throw new BusinessException("22", "dao22");  
        case 3:  
            throw new BusinessException("32", "dao32");  
        case 4:  
            throw new BusinessException("42", "dao42");  
        case 5:  
            throw new BusinessException("52", "dao52");  
        default:  
            throw new ParameterException("Dao Parameter Error");  
        }  
    }  
}  

 

 

 

  2.3Service层代码 

 

public interface TestService {  
    public void exception(Integer id) throws Exception;  
      
    public void dao(Integer id) throws Exception;  
}  
  
@Service("testService")  
public class TestServiceImpl implements TestService {  
    @Resource  
    private TestDao testDao;  
      
    public void exception(Integer id) throws Exception {  
        switch(id) {  
        case 1:  
            throw new BusinessException("11", "service11");  
        case 2:  
            throw new BusinessException("21", "service21");  
        case 3:  
            throw new BusinessException("31", "service31");  
        case 4:  
            throw new BusinessException("41", "service41");  
        case 5:  
            throw new BusinessException("51", "service51");  
        default:  
            throw new ParameterException("Service Parameter Error");  
        }  
    }  
  
    @Override  
    public void dao(Integer id) throws Exception {  
        testDao.exception(id);  
    }  
}  

 

 

 

  2.4 Controller层代码 

 

@Controller  
public class TestController {  
    @Resource  
    private TestService testService;  
      
    @RequestMapping(value = "/controller.do", method = RequestMethod.GET)  
    public void controller(HttpServletResponse response, Integer id) throws Exception {  
        switch(id) {  
        case 1:  
            throw new BusinessException("10", "controller10");  
        case 2:  
            throw new BusinessException("20", "controller20");  
        case 3:  
            throw new BusinessException("30", "controller30");  
        case 4:  
            throw new BusinessException("40", "controller40");  
        case 5:  
            throw new BusinessException("50", "controller50");  
        default:  
            throw new ParameterException("Controller Parameter Error");  
        }  
    }  
      
    @RequestMapping(value = "/service.do", method = RequestMethod.GET)  
    public void service(HttpServletResponse response, Integer id) throws Exception {  
        testService.exception(id);  
    }  
      
    @RequestMapping(value = "/dao.do", method = RequestMethod.GET)  
    public void dao(HttpServletResponse response, Integer id) throws Exception {  
        testService.dao(id);  
    }  
}  

 

 

 

  2.5 JSP页面代码 

 

<%@ page contentType="text/html; charset=UTF-8"%>  
<html>  
<head>  
<title>Maven Demo</title>  
</head>  
<body>  
<h1>所有的演示例子</h1>  
<h3>[url=./dao.do?id=1]Dao正常错误[/url]</h3>  
<h3>[url=./dao.do?id=10]Dao参数错误[/url]</h3>  
<h3>[url=./dao.do?id=]Dao未知错误[/url]</h3>  
  
  
<h3>[url=./service.do?id=1]Service正常错误[/url]</h3>  
<h3>[url=./service.do?id=10]Service参数错误[/url]</h3>  
<h3>[url=./service.do?id=]Service未知错误[/url]</h3>  
  
  
<h3>[url=./controller.do?id=1]Controller正常错误[/url]</h3>  
<h3>[url=./controller.do?id=10]Controller参数错误[/url]</h3>  
<h3>[url=./controller.do?id=]Controller未知错误[/url]</h3>  
  
  
<h3>[url=./404.do?id=1]404错误[/url]</h3>  
</body>  
</html>  

 

 

 

3、处理方式

 

 

3.1 使用SimpleMappingExceptionResolver实现异常处理 
1、在Spring的配置文件applicationContext.xml中增加以下内容: 

 

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
    <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->  
    <property name="defaultErrorView" value="error"></property>  
    <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->  
    <property name="exceptionAttribute" value="ex"></property>  
    <!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值 -->  
    <property name="exceptionMappings">  
        <props>  
            <prop key="cn.basttg.core.exception.BusinessException">error-business</prop>  
            <prop key="cn.basttg.core.exception.ParameterException">error-parameter</prop>  
  
            <!-- 这里还可以继续扩展对不同异常类型的处理 -->  
        </props>  
    </property>  
</bean>  

 

 

 

2、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。 

3、从上面的集成过程可知,使用SimpleMappingExceptionResolver进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,但该方法仅能获取到异常信息,若在出现异常时,对需要获取除异常以外的数据的情况不适用。

 

 

 

 

3.2 实现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);  
        }  
    }  
}  

 

2、在Spring的配置文件applicationContext.xml中增加以下内容: 

 

<bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>  

 


3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。 
4、从上面的集成过程可知,使用实现HandlerExceptionResolver接口的异常处理器进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提供更详细的异常处理信息。 


3.3 使用@ExceptionHandler注解实现异常处理 
1、增加BaseController类,并在类中使用@ExceptionHandler注解声明异常处理,代码如下:

 

public class BaseController {  
    /** 基于@ExceptionHandler异常处理 */  
    @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";  
        }  
    }  
}  

 

 

 

2、修改代码,使所有需要异常处理的Controller都继承该类,如下所示,修改后的TestController类继承于BaseController: 

 

public class TestController extends BaseController 

 


3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。 


4、从上面的集成过程可知,使用@ExceptionHandler注解实现异常处理,具有集成简单、有扩展性好(只需要将要异常处理的Controller类继承于BaseController即可)、不需要附加Spring配置等优点,但该方法对已有代码存在入侵性(需要修改已有代码,使相关类继承于BaseController),在异常处理时不能获取除异常以外的数据。

 

4、通过@ContrillerAdvice处理

 

针对3的情况对代码存在一定的侵入性,在spring3.2引入注解ControllerAdvice,可以在项目中添加如下代码:

 

@ControllerAdvice  
public class SpringExceptionHandler{  
  /** 
     * 全局处理Exception 
     * 错误的情况下返回500 
     * @param ex 
     * @param req 
     * @return 
     */  
    @ExceptionHandler(value = {Exception.class})  
    public ResponseEntity<Object> handleOtherExceptions(final Exception ex, final WebRequest req) {  
        TResult tResult = new TResult();  
        tResult.setStatus(CodeType.V_500);  
        tResult.setErrorMessage(ex.getMessage());  
        return new ResponseEntity<Object>(tResult,HttpStatus.INTERNAL_SERVER_ERROR); 
    }  
  
}  


只要扫描到该类即可,此为全局处理

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值