我在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");
}
现在假设springservlet和url映射是在web.xml中配置的,当我尝试通过url http://localhost:8080/server/admin?reqParam=xyz
访问servlet时,我在页面上得到了一个正确的错误。java.lang.Exception: Undeploy failed....
但是,当我试图通过HTTPClient访问代码时,也就是说,通过java代码,客户端中的响应无法捕获此异常,我只得到HTTP 401内部错误作为响应对象。但我希望在客户端中有一个Exception对象。
代码为:
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();
你能告诉我应该在哪里进行更改吗?这样就可以捕捉到客户端上的异常。
我可以用谷歌搜索,但找不到合适的答案。
不能通过HTTP引发异常。您需要做的是:
-
在服务器端,处理异常并确保HTTP响应具有适当的statusCode和/或响应头/正文。
-
在客户端,将该响应转换为所需的异常。
您应该研究HttpClient为异常处理提供了哪些接口。
我对这个问题的回答可能会对你的服务器端有所帮助:
https://stackoverflow.com/a/11535691/1506440