1

Here is what my controller method looks like:

@RequestMapping(value = "/com/uData.htm", method = RequestMethod.GET)
public @ResponseBody String getData(HttpServletRequest request, 
      HttpServletResponse response, @RequestParam(value="sn", required=true) String sn, 
      @RequestParam(value="serv", required=true) String serv,
      @RequestParam(value="date", required=false) String date) throws IOException{
try {
      Srring data =...;
      if(condition == false) {
         throw new IOException("my exception message");
    }
...
...

    } catch (IOException ie) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ie.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(ie.getMessage());
        response.flushBuffer();
    }

  return data;
}

And here is what my jQuery ajax looks like

$.ajax({
    cache: false,
    url: "/com/uData.htm",
    dataType: 'json',
    data: {"sn": sn, "serv": selServ},
    success: function(dt){
    result = dt;
  },
    error: function(jqXHR, textStatus, errorThrown) {
      if(jqXHR.responseText !== '') {
          alert(textStatus+": "+jqXHR.responseText);
    } else {
          alert(textStatus+": "+errorThrown);
       }  
     }
  });

The custom exception message that is returned is not alert in my jsp using the

alert(textStatus+": "+jqXHR.responseText);

How do I return the custom exception message ("my exception message") to the JSP?

2 Answers 2

1

Put it into the result of your method. Instead of returning String, return an object which has two String properties: result and exception.

That way, the client side success code can examine the exception.

Add more fields if you need more details (like exception type or additional information why the exception happened).

Sign up to request clarification or add additional context in comments.

2 Comments

So, we can't use the error function in jQuery to show the custom exception? Is there any way to push the exception message to the error function?
The error function isn't for handling errors in the server side code but for errors that happen while talking to the server (i.e. during sending/receiving the AJAX request).
0

Try parsing the response.responseText into an object so you can pull just the ExceptionMessage (your custom exception message).

            var message = $.parseJSON(jqXHR.responseText);
            alert(textStatus+': '+message.ExceptionMessage);

My code sample uses the jQuery.parseJSON method to extract the object from the JSON.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.