0

我在 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 访问 servlet 时 http://localhost:8080/server/admin?reqParam=xyz,我在页面上得到一个正确的错误。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();

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

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

4

1 回答 1

0

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

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

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

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

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

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

于 2012-07-20T07:04:59.980 回答