开发框架-异常处理机制

原则:

web层异常由统一的异常处理类捕获.

统一异常处理类针对java.lang.RunTimeException的几个常用子类进行了友好型提示封装.提供便利的统一的错误提示形势.

如果需要自定义异常提示,业务代码应该抛出框架自定义异常类:YKServiceException,并构造自定义异常信息.

统一异常处理类目前只针对ajax调用接口做统一处理.下面是一个统一异常处理类的大致处理逻辑.

public class CommonExceptionHandler implements HandlerExceptionResolver {
    Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        String errInfo = ex.getMessage();
        int errCode = 1000;
        if(ex.getClass().getName().equals(java.lang.IllegalArgumentException.class.getName())){
            errInfo = "请求参数不正确";
            errCode = 1100;
        }
        ServletOutputStream out;
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(errCode);
            out = response.getOutputStream();
            out.write(errInfo.getBytes("UTF-8"));
            out.flush();
        } catch (IOException e) {
            logger.info(ex.getMessage());
        }
        logger.info(ex.getMessage());

        return null;
    }

}

spring配置(java config):

@Configuration
public class BaseWebConfig  {

    @Bean
    public ApplicationContextAware getAppContextAware() {
        return new AppWebContextAware();
    }

    @Bean
    public AppContextDispose getAppContextDispose() {
        return new AppContextDispose();
    }

    @Bean
    public CommonExceptionHandler getCommonExceptionHandler() {
        return new CommonExceptionHandler();
    }
}

 

原理是实现自HandlerExceptionResolver 的bean,spring mvc会自动将异常全部导向该实现类.

 

引入统一处理机制后,业务代码如果捕获异常仅仅是写日志,则不需要捕获任何异常.

业务方法只返回业务数据,不要返回错误信息,要返回错误信息应该使用抛出异常方式,而不是使用函数的返回值.比如经常看到有的框架设计让每个方法附带返回一个isSuccess值,来确定是否有错误.这种方法不要使用.

如果捕获异常后可以做进一步处理则需要捕获异常.(比如重试,注入友好提示后重新抛出)

业务方法如果需要使用便利一致的友好错误提示,直接抛出预定义的错误类型

如果需要自定义友好错误提示则抛出YKServiceException,并构造自定义异常信息.

 

下面是一个实例,js端代码

    throwError : function() {
        var url = "simple/input/error2";
        $.ajax({
            url : url,
            dataType: 'json',
            dataFilter:function (data, type) {
                return data;
                
            },
            success:function (data, textStatus) {
                alert(data);
            },
            complete:function (XMLHttpRequest, textStatus) {
                alert(XMLHttpRequest.responseText);
                alert(XMLHttpRequest.status);
            }
        });
    }

控制器代码

    @RequestMapping("/error2")
    public Map<String, Object> throwException(HttpEntity<byte[]> requestEntity) {
//        throw new java.lang.IllegalArgumentException("");
       throw new YKServiceException("用户自定义异常说明");
    }

执行后客户端响应:

抛出一致性异常时

 

 

posted @ 2017-03-24 11:16  java林森  阅读(262)  评论(0)    收藏  举报