Aleksey Nikitenko Aleksey Nikitenko - 1 year ago 75
Java Question

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?


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


After create controller which needed for processing error from request:

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

Answer Source

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.


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

   <title>Page on which Error Occurs</title>



<%@ page isErrorPage="true" %>
<title>Show Error</title>
<p>Exception stack trace:<% exception.printStackTrace(response.getWriter()); %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download