0

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?

1 Answer 1

1

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);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.