简体   繁体   中英

throw exception as response from Spring handleRequest method

I have a scenario in Spring MVC , where I have to throw an Exception explicitly in the handleRequest Method.

For Eg.

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");

     }

Now assuming that spring servlet and url mapping is configured in web.xml, when i try to access the servlet via url http://localhost:8080/server/admin?reqParam=xyz , I get an correct error on page. java.lang.Exception: Undeploy failed....

But when I try to access the code via HTTPClient, that is via the java code the response in the client is not able to catch this exception and only I get is the HTTP 401 Internal Error as response object.But what i would Like to have is an Exception object in client.

Code is :

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();

Can you please let me know where the changes should be done so that the exception on the Client could be caught.

I could google but couldnt find a appropriate answer.

Exceptions can't be thrown over HTTP. What you'll need to do is:

  1. On the server side, handle the exception and make sure your HTTP response has an appropriate statusCode and/or response header/body.

  2. On the client side, translate that response into the exception you want.

You should investigate what interfaces HttpClient provides for exception handling.

My answer to this question might help you with the server side:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM