如何在 java 中捕获 400 个错误请求

How to catch 400 Bad request in java

我必须捕获 400 Bad 请求并相应地执行操作。

我有一个解决方案,它按预期工作:


try {

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

            }
}

但我不知道捕获 HttpStatusCodeException 然后检查状态代码是否是一个好方法。

有人可以建议另一种方法来处理 400 错误请求吗?

它是这样完成的,用 ControllerAdvice 声明 GlobalExceptionHandler


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

}

异常响应

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

在 api 代码捕获块中,您发现请求中缺少参数或密钥

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