异常与日志

在程序中如果遇到异常,摘取几个片断进行说明:

1.直接抛出底层异常,不打印日志,但前提是底层异常提供了  Xxxx(String msg)这样的构造方法,以便抛出时可以进一肯细化异常信息,以便调用方明确为什么发生异常。

protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
        for (HandlerAdapter ha : this.handlerAdapters) {
            if (logger.isTraceEnabled()) {
                logger.trace("Testing handler adapter [" + ha + "]");
            }
            if (ha.supports(handler)) {
                return ha;
            }
        }
        throw new ServletException("No adapter for handler [" + handler +
                "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    }

2.打印异常,并抛出异常

@Override
    public void process() throws BankApiException {
        try {
            BankRequest request = context.getRequest() ;
            String url = request.obtainUrl() ;
            context.setUrl(url);
        }catch(Exception e) {
            LOGGER.error(e.getMessage(), e); // 记录底层的异常
            //抛出新的转译后的异常通知调用者
            throw new BankApiException(BankApiErrType.URLCHECKERR.getValue(),"获取API URL失败") ;
        }
    }

注意体会 日志记录异常

原文地址:https://www.cnblogs.com/hzhuxin/p/8446325.html