【问题标题】:Throwing custom exception in servlet在servlet中抛出自定义异常
【发布时间】:2012-10-28 06:40:48
【问题描述】:

每当出现某些特定问题时,我想从 servlet 中抛出一个自定义的 exception,有点像下面这样。

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>

现在,当我在 servlet 的 doGet 方法的 throws 声明中添加 CustomException 时,就会出现问题。我收到以下错误:

Exception CustomException is not compatible with throws clause in HttpServlet.doGet(HttpServletRequest, HttpServletResponse)

现在我该如何克服这个问题?甚至可以自定义这样的异常并在抛出它时转发到错误页面?或者还有其他方法吗? 在此先感谢:)

【问题讨论】:

    标签: java jakarta-ee exception servlets servlet-3.0


    【解决方案1】:

    HttpServlet class doGet throws ServletException 声明如下:

        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[]

    【讨论】:

    • 问题,你能不能改为扩展RuntimeException,因为它们不必在签名中被捕获或声明?
    • @jschoen:当然可以,但我更愿意在这种情况下避免它们,因为类似于doGet 本身的异常会故意抛出ServletExcetion,因此会出现一些帖子行为。跨度>
    • 刚刚检查过。它不会重定向到错误页面。我错过了什么吗?
    • 好吧,我认为它实际上会重定向,但现在出现了这个问题:An error occurred at line: 14 in the jsp file: /WEB-INF/jsp/errorPage.jsp The method getErrors() is undefined for the type Throwable
    • @sha404: print exception.getClass().getName() 检查你遇到了哪个异常?我认为,您需要在那里进行类型转换:String errArray = (CustomException)exception.getErrors(); %>
    猜你喜欢
    • 2011-10-06
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2015-04-25
    • 2015-03-28
    • 1970-01-01
    相关资源
    最近更新 更多