JSP 提供聲明式錯誤處理:發生異常的頁面指定 errorPage,錯誤處理頁面宣告 isErrorPage="true" 即可獲得隱含物件 exception。
<%@ page isErrorPage="true" contentType="text/html; charset=UTF-8" %>
<html>
<head><title>系統錯誤</title></head>
<body>
<h2 style="color:red">系統發生錯誤!</h2>
<p><strong>錯誤訊息:</strong> ${exception.message} </p>
<p><strong>堆疊追蹤:</strong></p>
<pre>${exception.stackTrace}</pre>
<p><a href="javascript:history.back()">返回上一頁</a></p>
</body>
</html>
<%@ page errorPage="errorPage.jsp" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%
// 模擬業務邏輯異常
boolean errorCondition = true;
if (errorCondition) {
throw new RuntimeException("資料庫連線失敗:Connection refused");
}
%>
<p>正常內容(不會顯示)</p>
</body>
</html>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/errorPage.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/500.jsp</location>
</error-page>
isErrorPage="true" 的頁面才能使用 exception 隱含物件,否則編譯報錯。errorPage 支援相對/絕對路徑,建議以 /errorPage.jsp 絕對路徑避免路徑解析問題。@WebServlet("/GlobalExceptionHandler")
public class GlobalExceptionHandler extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
Throwable ex = (Throwable) req.getAttribute("javax.servlet.error.exception");
Integer code = (Integer) req.getAttribute("javax.servlet.error.status_code");
// 統一記錄日誌、回傳 JSON/頁面
}
}
web.xml 註冊:<error-page><location>/GlobalExceptionHandler</location></error-page>