Java 在servlet中引发自定义异常
每当发生特定问题时,我想从servlet抛出一个定制的Java 在servlet中引发自定义异常,java,jakarta-ee,exception,servlets,servlet-3.0,Java,Jakarta Ee,Exception,Servlets,Servlet 3.0,每当发生特定问题时,我想从servlet抛出一个定制的异常,有点像下面这样 public class CustomException extends Throwable { private String[] errArray; public CustomException(String[] errArray){ this.errArray = errArray; } public String[] getErrors(){ r
异常,有点像下面这样
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>
现在我该如何克服这个问题呢?甚至可以像这样自定义异常&在抛出异常时转发到错误页面吗?或者还有别的办法吗?
提前感谢:)HttpServlet
classdoGet
throwsServletException
如下所述:
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
请使您的CustomException
扩展ServletException
以符合方法规范
编辑:在您的error.jsp中,将错误获取为:
<% String[] errArray = null;
if(exception instanceof CustomException) {
errArray = (CustomException)exception.getErrors();
}
%>
请注意:它返回String[]
问题,您不能扩展运行时异常
,因为它们不必在签名中捕获或声明吗?@jschoen:当然可以,但是我更喜欢在这样的场景中避免它们,因为一些post行为是基于类似于doGet
本身的异常而预期的,该异常故意抛出ServletExcetion
。它不会重定向到错误页面。我遗漏了什么吗?嗯,我认为它实际上重定向了,但现在显示了这个问题:jsp文件:/WEB-INF/jsp/errorPage.jsp中的第14行出现了一个错误:/WEB-INF/jsp/errorPage.jsp方法getErrors()对于类型Throwable来说是未定义的。
@sha404:print exception.getClass().getName(),以检查出现了哪些异常?我认为,您需要在那里进行打字:
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
<% String[] errArray = null;
if(exception instanceof CustomException) {
errArray = (CustomException)exception.getErrors();
}
%>