0

I'm throwing response status exceptions in my codebase that look like this:

throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Resource not found!");
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Bad request!");

But, it generates this default spring json error:

{
    "type": "about:blank",
    "title": "Not Found",
    "status": 404,
    "detail": "Resource not found",
    "instance": "/api/graphql",
    "properties": null
}

I'd like to create my own exception handler because I don't want to show the fields: type, instance & properties.

I've tried creating my own exception handler for the ResponseStatusException.class here:

@ControllerAdvice
public class ResponseStatusHandler extends ResponseStatusExceptionHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @ExceptionHandler({ResponseStatusException.class})
    public ResponseEntity<Object> handle(ResponseStatusException e) {
        ObjectNode node = objectMapper.createObjectNode()
                .put("code", e.getStatusCode().value())
                .put("message", e.getMessage());

        return ResponseEntity.status(e.getStatusCode())
                .contentType(MediaType.APPLICATION_JSON)
                .body(node);
    }
}

But, it never seems to get invoked and only the default spring response is returned. Is it possible to add a custom exception handler for ResponseStatusException?

Reid2
  • 41
  • 4
  • you can see this article [@RestContollerAdvice not throwing custom exception](https://stackoverflow.com/questions/75430351/restcontolleradvice-not-throwing-custom-exception/75431515#75431515) – Peng Feb 16 '23 at 02:19

0 Answers0