3
我想從servlet中拋出一個自定義exception
,有點像下面這樣,只要出現一些特定的問題。在Servlet中拋出自定義異常
public class CustomException extends Throwable {
private String[] errArray;
public CustomException(String[] errArray){
this.errArray = errArray;
}
public String[] getErrors(){
return errArray;
}
}
然後當這個異常被拋出時,我想重定向用戶到一個特定的錯誤頁面。
<error-page>
<exception-type>com.example.CustomException</exception-type>
<location>/WEB-INF/jsp/errorPage.jsp</location>
</error-page>
這裏是錯誤頁面,我想用異常隱式對象。
<%@ page isErrorPage="true" %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<my:head title="Error"></my:head>
<body>
<% String errArray = exception.getErrors(); %>
</body>
</html>
現在,當我去到throws
聲明servlet的doGet
方法添加CustomException
出現問題。我得到以下錯誤:
Exception CustomException is not compatible with throws clause in HttpServlet.doGet(HttpServletRequest, HttpServletResponse)
現在我該如何克服這個問題?當拋出它時,甚至可以自定義異常,例如這個&轉發到錯誤頁面?或者還有其他方法嗎? 感謝提前:)
問題,不能代替你'延長RuntimeException',因爲他們不必須在簽名中被捕或宣佈? –
@jschoen:當然你可以,但我更喜歡在這樣的場景中避免它們,在這種情況下,基於類似於'doGet'本身的異常故意引發'ServletExcetion'的異常。 –
剛剛檢查。它不會重定向到錯誤頁面。我錯過了什麼嗎? – sha256