Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

การจัดการ Exception ใน JSP ด้วย <c:catch>

Tag <c:catch> (JSTL Core) จับ Throwable ที่เกิดใน body เก็บไว้ใน variable (optional) ใช้สำหรับ error handling แบบ graceful

Attribute

AttributeคำอธิบายRequiredDefault
varVariable name เก็บ Throwable (java.lang.Throwable)No-

ตัวอย่าง

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>Catch Exception</title></head>
<body>
    <c:catch var="catchException">
        <% int x = 5 / 0; %>  <!-- Scriptlet ที่จะ throw exception -->
    </c:catch>
    
    <c:if test="${catchException != null}">
        <p>Exception caught: <c:out value="${catchException}"/><br/>
        Message: <c:out value="${catchException.message}"/></p>
    </c:if>
</body>
</html>

ผลลัพธ์

Exception caught: java.lang.ArithmeticException: / by zero
Message: / by zero

จุดสำคัญ

  • จับ Throwable ทุกชนิด (Error, Exception, RuntimeException)
  • Body ใส่ได้ทั้ง scriptlets, EL, JSTL tags, template text
  • ถ้าไม่มี var exception จะถูกกลืน (swallowed) - ระวัง silent failures
  • หลัง catch execution จะต่อไปหลัง </c:catch> ต่อ (ไม่หยุด request)

ข้อจำกัดและแนวทางที่ดีกว่า

  • ไม่แนะนำ ใช้ scriptlets ใน body ควรย้าย logic ไป Java class/Controller
  • Production: ใช้ Error pages (web.xml <error-page>) หรือ @ControllerAdvice (Spring)
  • <c:catch> เหมาะสำหรับ: non-critical sections, third-party tag libraries, graceful degradation
  • Logging: ควร log exception ที่จับได้ ไม่แค่แสดง

Alternative: Page Directive errorPage

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

จับ uncaught exceptions ทั้งหน้า redirect ไป error page