[英]Spring Exception Handling using @ControllerAdvice
I have created an APIExceptionHandler class to handle custom Runtime Exceptions .我创建了一个APIExceptionHandler class 来处理自定义运行时异常。 One of the Exception classes that I have created is PasswordMismatchException .我创建的异常类之一是PasswordMismatchException 。 So whenever an exception is encountered I return a response of type APIResponse .因此,每当遇到异常时,我都会返回APIResponse类型的响应。
Now my question is why the expected Response is not getting generated when using CompletableFuture .现在我的问题是为什么使用CompletableFuture时没有生成预期的响应。
APIResponse.java APIResponse.java
@AllArgsConstructor
@Getter
@Setter
public class APIResponse {
private Map<String, String> response;
}
Exception Handler (CompletableFuture)异常处理程序(CompletableFuture)
@ExceptionHandler(PasswordMismatchException.class)
public CompletionStage<ResponseEntity<APIResponse>> passwordMismatchExceptionHandler(PasswordMismatchException exception) {
return CompletableFuture.completedFuture(Collections.singletonMap(MESSAGE_FIELD, exception.getMessage()))
.thenApply(APIResponse::new)
.thenApply(response -> new ResponseEntity<>(response, HttpStatus.BAD_REQUEST));
}
Response (not as expected)响应(与预期不同)
{
"done": true,
"cancelled": false,
"completedExceptionally": false,
"numberOfDependents": 0
}
Exception Handler (normal)异常处理程序(正常)
@ExceptionHandler(PasswordMismatchException.class)
public ResponseEntity<APIResponse> passwordMismatchExceptionHandler(PasswordMismatchException exception) {
Map<String, String> errorMessageMap = Collections.singletonMap(MESSAGE_FIELD, exception.getMessage());
APIResponse response = new APIResponse(errorMessageMap);
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
Response (as expected)响应(如预期)
{
"response": {
"message": "Password did not match with Repeated Password."
}
}
In spring boot the ObjectMapper
by default used the getters
and setters
for Serialization and Deserialization , while the response type is CompletionStage
the object mapper will be serializing corresponding child object (for example CompletableFuture ) and serializing method starts with get
and is
In spring boot the ObjectMapper
by default used the getters
and setters
for Serialization and Deserialization , while the response type is CompletionStage
the object mapper will be serializing corresponding child object (for example CompletableFuture ) and serializing method starts with get
and is
public boolean isDone()
public boolean isCancelled()
public boolean isCompletedExceptionally()
public int getNumberOfDependents()
And since then name of method is get
which returns the final object, the objectmapper
is simply ignoring it从那时起,方法的名称是get
,它返回最终的 object, objectmapper
只是忽略它
public T get() throws InterruptedException, ExecutionException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.