我們不會希望當後端出現錯誤的時候讓USER看一大堆後端系統錯誤訊息,對於使用者來說使用者體驗會非常差,所以能夠明確表達錯誤在哪裡就需要客製一下錯誤訊息頁面,這就是今天想要探討的內容囉。
讓Client端知道出現Error的原因,Client端錯誤响應(4XX)、Server端的錯誤响應(5XX)
@WebServlet("/ClientErrorServlet")
public class ClientErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("=====ClientErrorServlet=====");
//res.sendError(res.SC_NOT_FOUND);
res.sendError(res.SC_NOT_FOUND,"使用者請求參數錯誤");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<error-page>
<error-code>404</error-code>
<location>/4xx.html</location>
</error-page>
<error-page>
<exception-type>jakarta.servlet.ServletException</exception-type>
<location>/5xx.html</location>
</error-page>
</web-app>
@WebServlet("/ServerErrorServlet")
public class ServerErrorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
throw new ServletException();
}
}
訪問不存在頁面,部署描述檔設定前
訪問不存在頁面,部署描述檔設定後
訪問ServerErrorServlet,部署描述檔設定前
訪問ServerErrorServlet,部署描述檔設定後