Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Response status code using @ControllerAdvice and @ResponseStatus

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

like image 742
Melad Basilius Avatar asked Nov 08 '22 16:11

Melad Basilius


1 Answers

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());
like image 141
0gam Avatar answered Nov 14 '22 23:11

0gam