2016-08-04 8 views
0

ich ein Servlet api, wo ich verwenden, um meine eigenen Ausnahmen von Servlets Ebene zu werfenException-Handler arbeitet für doGet(), aber nicht für doPost()

Wenn ich Ausnahme von doGet Methode funktioniert alles einwandfrei und Exception-Handler werfen Fänge und verarbeitet meine Ausnahme. Das Problem tritt auf, wenn ich die Ausnahme von der doPost-Methode ausleite. in diesem Fall leider nicht sehen Fehlerseite Ich

nie

web.xml

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

Exception-Handler

@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); 
    } 
} 

Servlets

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

Antwort

1

auf Fügen Sie Ihre 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); 
} 

Um Code-Duplizierung erwägen die Schaffung dritte Methode

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); 
} 

und rufen Sie es von beiden doGet() und 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);  
} 
zu vermeiden
Verwandte Themen