简体   繁体   中英

Spring ExceptionHandler does not return valid response code

I have such Exception handler in spring RestController.

   @ExceptionHandler(AuthException.class)
public ResponseEntity<String> handleCustomException(AuthException ex, Writer writer) throws IOException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    ResponseEntity responseEntity = new ResponseEntity(headers, HttpStatus.FORBIDDEN);
    (new ObjectMapper()).writeValue(writer, ex.getAsMap());

    return responseEntity;
}

I expect result: Content-type: application-json Status: 403 And body:

{"date":"06-06-2019 18:36:34","errorCode":"102","error":"Login or password is not right","message":"Access denied"}

But result is: Status: 200 and Content-type is not set. Any suggestions?

Can you try like this. This is a code snippet, modify it as per the requirements.

@ControllerAdvice
    public class GlobalExceptionHandler{
        @ExceptionHandler(MyCustomException.class)
        @ResponseBody
        public ResponseEntity<?> handleCustomException(MyCustomException e) {        
            String bodyJson = "Fatal Exception while performing.";
            return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON).body(bodyJson);
        }
    }

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