Balconsky
Balconsky

Reputation: 2244

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?

Upvotes: 0

Views: 350

Answers (1)

Sambit
Sambit

Reputation: 8001

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

Upvotes: 1

Related Questions