Announcement Announcement Module
Collapse
No announcement yet.
Returning JSON in an ExceptionHandler Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Returning JSON in an ExceptionHandler

    I am in Jetty (though I am not sure that's actually relevant).

    The objective is to return a specific HTTP error code (which is contained in the exception object), the right JSON payload (an description of the error) with the appropriate Content-Type etc.

    This doesn't appear possible. I have tried:
    - return a regular object just I do in my controller methods hoping it will get mapped to JSON - that fails it can't find the right mapper
    - return a ModelAndView that maps to a freemarker page with a single $json variable - sort of works but it's ghetto and returns the wrong content type
    - do everything in the handler (set the content type, get the output stream, jam the JSON down the stream and flush, return void) and the page that gets returned is still the JSON error page (with the stuff I cram down the stream)

    I'd love to figure out what the right way is to handle this.

    Thanks,
    Benjamin

  • #2
    Hi, this is one way of do that

    Create a class that contains the code and the error.
    Code:
    	public class RestError
    	{
    		private int errorCode;
    
    		private String errorMessage;
    	}
    In your controller put this
    Code:
    	private ObjectMapper objectMapper = new ObjectMapper();
    
    	private JsonEncoding encoding = JsonEncoding.UTF8;
    
    	@ExceptionHandler(Exception.class)
    	public void handleException(Exception ex, HttpServletResponse response) throws IOException
    	{
    	       RestError error = new RestError();
    		error.setErrorCode(errorCode);
    		error.setErrorMessage(ex.getLocalizedMessage());
    
    		JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), encoding);
    		objectMapper.writeValue(generator, error);
    		generator.flush();
    		response.setStatus(ERROR_CODE);
    	}
    Hope this help you.

    Comment

    Working...
    X