Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中捕获400个错误请求_Java_Rest_Spring Boot Actuator_Bad Request - Fatal编程技术网

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

如何在java中捕获400个错误请求,java,rest,spring-boot-actuator,bad-request,Java,Rest,Spring Boot Actuator,Bad Request,我必须捕获400错误请求并相应地执行操作 我有一个解决方案,它按预期工作: try { //some rest api code } catch (HttpStatusCodeException e) { if (e.getStatusCode() == HttpStatus.BAD_REQUEST) { // Handle Bad Request and perform operation according to that..

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

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


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);
    }
}
例外响应

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());


HttpStatusCodeException
是一个抽象类
HttpClientErrorException.BadRequest
是一个可以直接捕获的具体异常。
throw new  KeyNotFoundException ("Key not found in the request..."+ex.getMessage());