【问题标题】:throw exception as response from Spring handleRequest method抛出异常作为来自 Spring handleRequest 方法的响应
【发布时间】:2012-07-20 06:36:04
【问题描述】:

我在 Spring MVC 中有一个场景,我必须在 handleRequest 方法中显式抛出一个异常。

例如。

public class AdminController implements Controller {

public ModelAndView handleRequest(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

   // for some request parameter this is run. For Eg. reqParam=xyz
    undeployTables();
}

public void undeployTables() throws Exception {
      throw new Exception("Undeploy Exception");

     }

现在假设在 web.xml 中配置了 spring servlet 和 url 映射,当我尝试通过 url http://localhost:8080/server/admin?reqParam=xyz 访问 servlet 时,我在页面上得到一个正确的错误。 java.lang.Exception: Undeploy failed....

但是当我尝试通过 HTTPClient 访问代码时,即通过 java 代码,客户端中的响应无法捕获此异常,只有我得到的是 HTTP 401 内部错误作为响应对象。但我会喜欢的是客户端中的一个异常对象。

代码是:

HttpPost httppost = new HttpPost(url.toURI());
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
logger.info("executing request " + httppost.getURI()); //$NON-NLS-1$
// Create a response handler
HttpResponse response = httpclient.execute(httppost);// expect exception to be thrown here
statusCode = response.getStatusLine().getStatusCode();

您能否告诉我应该在哪里进行更改,以便捕获客户端上的异常。

我可以谷歌但找不到合适的答案。

【问题讨论】:

    标签: java exception servlets spring-mvc apache-httpclient-4.x


    【解决方案1】:

    不能通过 HTTP 抛出异常。你需要做的是:

    1. 在服务器端,处理异常并确保您的 HTTP 响应具有适当的 statusCode 和/或响应标头/正文。

    2. 在客户端,将该响应转换为您想要的异常。

    您应该调查 HttpClient 为异常处理提供了哪些接口。

    我对这个问题的回答可能会对你在服务器端有所帮助:

    https://stackoverflow.com/a/11535691/1506440

    【讨论】:

    • 如果servlet直接抛出异常怎么办? HTTPClient 可以捕获异常作为响应吗?这不是正确的方法吗?
    • 不,不是Java调用Java,是Java调用Web服务——Web服务恰好也是用Java实现的……如果你想返回错误,你需要使用HTTP来去做吧。
    猜你喜欢
    • 2013-01-31
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2020-01-28
    • 2014-10-20
    • 1970-01-01
    相关资源
    最近更新 更多