tag in web.xml doesn't catch java.lang.Throwable Exceptions

后端 未结 2 688
無奈伤痛
無奈伤痛 2020-12-11 09:51

I have a web-app developed with servlet & JSP. I configured my app to throw an IllegalArgumentException if I insert bad parameters. Then I configured my web

2条回答
  •  遥遥无期
    2020-12-11 10:29

    You should not catch and suppress it, but just let it go.

    I.e. do not do:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            doSomethingWhichMayThrowException();
        } catch (IllegalArgumentException e) {
            e.printStackTrace(); // Or something else which totally suppresses the exception.
        }
    }
    

    But rather just let it go:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doSomethingWhichMayThrowException();
    }
    

    Or, if you actually intented to catch it for logging or so (I'd rather use a filter for that, but ala), then rethrow it:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            doSomethingWhichMayThrowException();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw e;
        }
    }
    

    Or, if it's not an runtime exception, then rethrow it wrapped in ServletException, it will be automatically unwrapped by the container:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            doSomethingWhichMayThrowException();
        } catch (NotARuntimeException e) {
            throw new ServletException(e);
        }
    }
    

    See also:

    • How does server prioritize which type of web.xml error page to use?
    • Submitting form to Servlet which interacts with database results in blank page

提交回复
热议问题