如何在 JSP 文件中捕获异常?

Ale*_*nko 5 java spring jsp exception-handling exception

我使用 ExceptionHandler 在控制器中捕获异常。

@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;
}
Run Code Online (Sandbox Code Playgroud)

但是,例如,如果在 jsp 文件中我想从 null 对象获取数据,那是异常而不是 cathcing。

我需要建议,如何在jsp 文件中捕获异常?或者我只需要在控制器中捕获所有错误?

更新:

最好的解决方案是放在 web.xml uri 中以解决错误。

<error-page>
    <location>/error</location>
</error-page>
Run Code Online (Sandbox Code Playgroud)

创建需要处理请求错误的控制器后:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Arp*_*wal 2

添加到 @astrohome 答案,JSP还为您提供了为每个 JSP 指定错误页面的选项。每当页面抛出异常时,JSP 容器就会自动调用错误页面。

要设置错误页面,请使用该<%@ page errorPage="xxx" %>指令。

您上面提到的错误处理 JSP 中包含该指令<%@ page isErrorPage="true" %>

例如,假设您有一个 JSP 页面名称,main.jsp您试图在该页面上对 null 对象执行操作。

主.jsp

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

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

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

显示错误.jsp

<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error</title>
</head>
<body>
<p>Exception stack trace:<% exception.printStackTrace(response.getWriter()); %>
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)