0

In the code below I'm exposing a POST endpoint. The return value of the POST is determined by a Boolean attribute on the Success object :

@RequestMapping(value="/new", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String createDispatch(@RequestParam(value="p1") String p1) {

    Success ds = new Success();
    //Set a boolean on Success object to true
    ObjectMapper mapper = new ObjectMapper();

    try {
        return mapper.writeValueAsString(ds);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
        return {"exception": "true"};
    } catch (JsonMappingException e) {
        e.printStackTrace();
        return {"exception": "true"};
    } catch (IOException e) {
        e.printStackTrace();
        return {"exception": "true"};
    }

}

Catching each exception type when writing converting to JSON (return mapper.writeValueAsString(ds) ) seems redundant as if there is an issue with creating the JSON String (one of the exception clauses matches) then I'm unable to return what the issue is to the client, as I cannot wrap the exception in a Json object. So I just return return {"exception": "true"}; .

What should I return in order to encapsulate the type of exceptions that should be thrown ?

Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60
blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

1

You can handle exceptions in spring controller with @ExceptionHandler and return status as HTTP response status code, or any object, or even as Exception serialized to JSON.

@RequestMapping(value="/new")
@ResponseBody
public String createDispatch(@RequestParam(value="p1") String p1) {
    Success ds = new Success();
    ObjectMapper mapper = new ObjectMapper();    
    return mapper.writeValueAsString(ds);
}      

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleAnyException(Exception exception) {
    return formatExceptionAsJson(exception);
}
Lea32
  • 96
  • 2
0

If you handle every exception in the same way and you just want the relevant information you may use

    try {
        return mapper.writeValueAsString(ds);
    } catch (Exception e) {
        e.printStackTrace();
        return {"exception":"true", "exceptionClass":e.getClass().getName(),
                "exceptionMessage":e.getMessage()};
    }

This way you will have some relevant information about the exception which occured.

You may return a json of any DTO which you deem useful.

Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60