0

My spring boot @RestControllerAdvice is overriding the @ResponseStatus of my Exception class (that extends RuntimeException). It is defaulting to 200. But it works when it put the @ResponseStatus over the handler method.

@ExceptionalHandler(MyCustomException.class)
@ResponseStatus(value = Http.BAD_REQUEST)
public MyCustomErrorClass handleMyCustomException( MyCustomException e) {
 return buildMyCustomErrorClass(e); 
} 

Can I please know what's the correct usage? Where Should I place the @ResponseStatus? On the exception, on the controller or both? I thought the annotation over exception is a clean way.

sagar
  • 79
  • 3
  • 8

1 Answers1

0

You can use ResponseEntity as the return of the method like this.

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Object> handleCustomException(CustomException ex) {
        HttpStatus status = HttpStatus.BAD_REQUEST; // Set the desired status code here
        
        // You can also provide a custom response body if needed
        ApiError apiError = new ApiError(status, "Custom exception occurred", ex.getMessage());
        
        return new ResponseEntity<>(apiError, status);
    }

Or if you want to use @ResponseStatus annotation, add the annotation for the Exception class like this.

@ResponseStatus(HttpStatus.BAD_REQUEST) // Set the desired status code here
public class CustomException extends RuntimeException {
    // Your custom exception code here
}


Or otherwise, you can use HttpServletResponse like this.


    @ExceptionHandler(CustomException.class)
    public void handleCustomException(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST); // Set the desired status code here
        response.getWriter().write("Custom exception occurred"); // Set the response body if needed
        // You can also set headers or other response properties here
    }
Mafei
  • 3,063
  • 2
  • 15
  • 37