Mamun Kayum
Mamun Kayum

Reputation: 161

what is the best practice to return error message string from Spring Controller for an ajax call?

I have a Spring controller from where I'm returning a String. Basically I'm using JSONObject and JSONArray and finally making a String and returning it. Like:

@RequestMapping(value = "getValue")
    public @ResponseBody
    String getValue(){

    JSONObject jassonObject = new JSONObject();

    JSONArray jassonArray = new JSONArray();

    jassonObject.put("mykey",jassonArray);

    And finally:
    return jassonObject.toString();
}

But suppose while generating this JSONObject if I get any exception I want to return that exception message. That is :

try {
JSONObject jassonObject = new JSONObject();

JSONArray jassonArray = new JSONArray();

jassonObject.put("mykey",jassonArray);

return jassonObject.toString();
} catch(Exception ex) {
return the exception?
}

My question is that how to return this exception value properly as error and get this properly from ajax call error function?

Upvotes: 0

Views: 1152

Answers (2)

Mamun Kayum
Mamun Kayum

Reputation: 161

Alright, after learning a bit I found that, in case of having an exception while generating the JSONObject for an Ajax request, we should respond with a http Bad Request response code. Like in my case:

try {
JSONObject jassonObject = new JSONObject();

JSONArray jassonArray = new JSONArray();

jassonObject.put("mykey",jassonArray);

return jassonObject.toString();
} catch(Exception ex) {
       jassonObject.put("errorMessageKey", e.getMessage()); // generating      
                                        //json object with error message
         response.setStatus(400); // bad request
         response.setContentType("application/json");
         response.setCharacterEncoding("UTF-8");
         response.getWriter().write(jassonObject.toString()); 
}

Upvotes: 0

Valath
Valath

Reputation: 920

Ajax callback handlers depends up on http status codes. Other than 200 OK will trigger error call back. You may have different error handlers for each http status code. Also it is always advisable to return non 200 OK code in case of errors.

Please find sample in the below link : How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Upvotes: 1

Related Questions