手動處理異常的使用,手動處理使用
在程式運行過程中,不免遇到一些錯誤,這時候就要對錯誤進行一些處理,使得錯誤能夠更友好的展示給使用者。所以在這介紹一下手動錯誤處理的使用:1、建立錯誤處理程式的類,繼承自RuntimeException ,如下
public class ApplicationException extends RuntimeException { public ApplicationException() { } public ApplicationException(String message) { super(message); } public ApplicationException(Throwable cause) { super(cause); } public ApplicationException(String message, Throwable cause) { super(message, cause); } public ApplicationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); }}
2、錯誤處理配置
<!-- 錯誤跳轉頁面的配置 --> <error-page> <exception-type>com.bjpowernode.drp.util.ApplicationException</exception-type> <location>/error.jsp</location> </error-page>
3、錯誤處理程式error.jsp(簡單攔截)
<div align="center"><p align="left"><span class="STYLE1">錯誤資訊:</div> <div><%=exception.getMessage()%></div>
4、除此之外,還有對一些錯誤碼的如理,如下: 1)設定檔中對錯誤碼的配置
<!-- 錯誤跳轉頁面的配置 --> <error-page> <error-code>404</error-code> <location>/http_error.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/http_error.jsp</location> </error-page>
2)錯誤處理頁面http_error.jsp的處理
<body> <% Integer errorCode=(Integer)request.getAttribute("javax.servlet.error.status_code"); //當分別遇到錯誤碼為404和500時,分別跳轉到相應的錯誤處理頁面進行處理 if (errorCode==404){ response.sendRedirect(request.getContextPath()+ "/404.jsp"); }else if (errorCode==500){ response.sendRedirect(request.getContextPath()+ "/500.jsp"); } %> </body>
3)錯誤處理頁面處理 如果是404:<body> 未找到請求的頁面</body> 如果是500:<body>系統出現錯誤,請與系統管理員聯絡!</body>