【问题标题】:How to catch 400 Bad request in java如何在 java 中捕获 400 错误请求
【发布时间】:2021-04-22 08:06:53
【问题描述】:

我必须捕获 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 Bad request 的方法吗?

【问题讨论】:

  • HttpStatusCodeException 是一个抽象类。 HttpClientErrorException.BadRequest 是一个可以直接捕获的具体异常。

标签: java rest spring-boot-actuator bad-request


【解决方案1】:

就这样完成了,用 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2017-12-11
    • 2021-01-20
    • 1970-01-01
    相关资源
    最近更新 更多