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

hec6srdp  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(412)

我必须捕获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个错误的请求吗?

pw9qyyiw

pw9qyyiw1#

它是这样完成的,用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代码catch块中,您发现请求中缺少参数或键

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

相关问题