2016-08-04 52 views
0

我有一个Servlet API的,我用来从servlet的水平异常处理工程的doGet(),但不适合的doPost()

把我自己的异常当我抛出的异常从doGet方法的一切工作正常和异常处理程序捕获并处理我的异常。当我抛出doPost方法的异常时,该问题就会出现。在这种情况下,可惜的是我从来没有看到错误页面

的web.xml

<error-page> 
    <exception-type>java.lang.Throwable</exception-type > 
    <location>/ErrorHandler</location> 
</error-page> 

异常处理程序

@WebServlet("/ErrorHandler") 
public class ErrorHandler extends HttpServlet { 

    private final Logger logger; 

    public ErrorHandler() { 
     logger = Logger.getLogger(ErrorHandler.class); 
    } 

    @Override 
    public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { 
     Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION); 
     logger.error("occurred exception: ", throwable); 
     httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse); 
    } 
} 

的Servlet

@Override 
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { 
    throw new UserException("error message"); 
} 

回答

1

添加到您的ErrorHandler

@Override 
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { 
    Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION); 
    logger.error("occurred exception: ", throwable); 
    httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse); 
} 

为了避免重复代码考虑创建第三方法

private void processError(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { 
    Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION); 
    logger.error("occurred exception: ", throwable); 
    httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse); 
} 

和从两个doGet()doPost()

@Override 
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { 
    processError(req, resp);  
} 

@Override 
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { 
    processError(req, resp);  
} 
调用它