Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can catch exception in JSP files?

I used ExceptionHandler for catch exception in controllers.

@ExceptionHandler(value = {Exception.class, RuntimeException.class})
public final ModelAndView globalExceptionHandler(final Exception exception) {
    ModelAndView modelAndView = new ModelAndView("error/500");
    modelAndView.addObject("tl_exception", errorSystem.processingError(exception));
    return modelAndView;
}

But, for example, if in jsp file i am tring to get data from null object, that's exception not cathcing.

I need advice, how i can catch exception in jsp file? Or all error i need catching only in controllers?

Update:

The best solution is put in web.xml uri for errors.

<error-page>
    <location>/error</location>
</error-page>

After create controller which needed for processing error from request:

@Controller
public final class ErrorController {
    @RequestMapping(value = "/error")
    public final ModelAndView globalErrorHandle(final HttpServletRequest request) {
       String page = "error/500";
       final String code = request.getAttribute("javax.servlet.error.status_code").toString();
       if (null != code && !code.isEmpty()) {                
            final Integer statusCode = Integer.parseInt(code);
            switch (statusCode) {
                case 404 : page = "error/404";
                case 403 : page = "error/403";
            }
        }
        return new modelAndView(page);
    }
}
like image 923
Alexey Nikitenko Avatar asked Aug 16 '15 18:08

Alexey Nikitenko


1 Answers

Adding to @astrohome answer, JSP also gives you an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP container automatically invokes the error page.

To set up an error page, use the <%@ page errorPage="xxx" %> directive.

And on Error Handling JSP which you mentioned above include the directive <%@ page isErrorPage="true" %>.

Example, let's say you have a JSP page name main.jsp on which you are trying to perform operation on null object.

main.jsp

<%@ page errorPage="show-error.jsp" %>

<html>
<head>
   <title>Page on which Error Occurs</title>
</head>
<body>

</body>
</html>

show-error.jsp

<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error</title>
</head>
<body>
<p>Exception stack trace:<% exception.printStackTrace(response.getWriter()); %>
</p>
</body>
</html>
like image 144
Arpit Aggarwal Avatar answered Oct 24 '22 14:10

Arpit Aggarwal