2016-08-04 48 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);  
} 
調用它