Search code examples
javaspringpostjacksonendpoints

Handling multiple exceptions thrown by Jackson on Spring endpoint


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 ?


Solution

  • 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);
    }