简体   繁体   English

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

[英]How to catch 400 Bad request in java

I have to catch the 400 Bad request and perform operation accordingly.我必须捕获 400 Bad 请求并相应地执行操作。

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.但我不知道捕获 HttpStatusCodeException 然后检查状态码是否是一种好方法。

Can someone suggest another way to handle 400 Bad request?有人可以提出另一种处理 400 Bad request 的方法吗?

its done like this, Declare GlobalExceptionHandler with ControllerAdvice它是这样完成的,使用 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 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在 api 代码捕获块中,您发现参数丢失或请求中缺少密钥

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM