如何在java中捕获400个错误请求
我必须捕获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..
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());