I am using spring mvc, to handle excpetion i use global exception handler
@ControllerAdvice
public class GlobalControllerExceptionHandler {
    @ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation")
    @ExceptionHandler({DataIntegrityViolationException.class})
    public @ResponseBody AdminResponse handleConflict(DataIntegrityViolationException ex,HttpServletResponse httpServletResponse) {
        AdminResponse error = new AdminResponse ();
        httpServletResponse.setStatus(HttpStatus.CONFLICT.value());
        error.setStatus(Status.FAILURE);
        error.setErrorDescription(ex.getMessage());
        return error;
    }
as i know, the annotation  @ResponseStatus(value = HttpStatus.CONFLICT will change the repose status code into HttpStatus.CONFLICT, but that is not happen.
when i created dummy exception and annotated this dummy exception with @ResponseStatus then throw this new exception, the GlobalControllerExceptionHandler catches and handle the exception and also changes the response status code.
how can i change the response status code without creating new Exception, i just need to catch DataIntegrityViolationException
You take to two way.
1. use @ResponseBody and return custom JSON String.
@ExceptionHandler(value = { HttpClientErrorException.class, HTTPException.class })
public @ResponseBody String checkHTTPException(HttpServletRequest req, Exception exception,
        HttpServletResponse resp) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    CommonExceptionModel model = new CommonExceptionModel();
    model.setMessage("400 Bad Request");
    model.setCode(HttpStatus.BAD_REQUEST.toString());
    String commonExceptionString = mapper.writeValueAsString(model);
    return commonExceptionString;
}
2. use ResponseEntity and exception
Return ResponseEntity.
ResponseEntity.status(exception.getStatusCode()).headers(exception.getResponseHeaders())
                            .body(exception.getResponseBodyAsString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With