简体   繁体   中英

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM