Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have to catch the 400 Bad request and perform operation accordingly.

I have one solution and it is working as expected:


try {

//some rest api code
} catch (HttpStatusCodeException e) {
            if (e.getStatusCode() == HttpStatus.BAD_REQUEST) {
                // Handle Bad Request and perform operation according to that..

            }
}

But I don't know if it is good approach to catch HttpStatusCodeException and then check on status code or not.

Can someone suggest another way to handle 400 Bad request?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
566 views
Welcome To Ask or Share your Answers For Others

1 Answer

its done like this, Declare GlobalExceptionHandler with ControllerAdvice


@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(KeyNotFoundException.class)
    public ResponseEntity<ExceptionResponse> keyNotFound(KeyNotFoundException ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setStatusCode(HttpStatus.BAD_REQUEST.toString().substring(0,3));
        response.setError(HttpStatus.BAD_REQUEST.getReasonPhrase());
        response.setMessage(ex.getMessage());
        response.setTimestamp(LocalDateTime.now());
        return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
    }
}

KeyNotFoundException


public class KeyNotFoundException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public KeyNotFoundException(String message) {
        super(message);
    }

}

ExceptionResponse

public class ExceptionResponse {
    
    private String error;
    private String message;
    private String statusCode;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
    private LocalDateTime timestamp;
    
// getters and setters

in api code catch block where you find parameter is missing or key is missing from request

throw new  KeyNotFoundException ("Key not found in the request..."+ex.getMessage());


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...