Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return text as json in exception handler

I have text in json format and I want send it to the client as json format. I searched around and found that converting it into java object and then returning it is working fine. Can I avoid this process of serialization & deserialization anyhow. I also tried adding @ResponseBody and it did not work.

Current exception handler code:

@ExceptionHandler({CustomRuntimeException.class})
@ResponseBody
public Object handleRuntimeException(CustomRuntimeException exception) {
    String jsonString = exception.getResponseJson();
    ObjectMapper objectMapper = new ObjectMapper();
    Object response = objectMapper.readValue(jsonString, CustomResponse.class); 
    return response;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can always use ResponseEntity with content type of json, now the text should be properly parsed by the client based on this.

@ExceptionHandler({CustomRuntimeException.class})
@ResponseBody
public Object handleRuntimeException(CustomRuntimeException exception) {
    String jsonString = exception.getResponseJson();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<Object>(responseBody, headers, HttpStatus.BAD_REQUEST);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading