How to change the content type in exception handler

前端 未结 2 1910
渐次进展
渐次进展 2020-12-13 18:19

Suppose I have a controller that serves GET request and returns bean to be serialized to JSON and also provides an exception handler for IllegalArgumentEx

2条回答
  •  时光取名叫无心
    2020-12-13 19:18

    I think removing the produces = MediaType.APPLICATION_JSON_VALUE from @RequestMapping of the getMetaInformation will give you the desired result.

    The response-type will be negotiated according to the content-type value in the Accept header.


    edit

    As this does not cover scenario 3,4 here is a solution working with ResponseEntity.class directly:

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleIllegalArgumentException(Exception ex) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity(ex.getMessage(), headers, HttpStatus.BAD_REQUEST);
    }
    

提交回复
热议问题