簡體   English   中英

Spring 使用@ControllerAdvice 處理異常

[英]Spring Exception Handling using @ControllerAdvice

我創建了一個APIExceptionHandler class 來處理自定義運行時異常 我創建的異常類之一是PasswordMismatchException 因此,每當遇到異常時,我都會返回APIResponse類型的響應。

現在我的問題是為什么使用CompletableFuture時沒有生成預期的響應

APIResponse.java

@AllArgsConstructor
@Getter
@Setter
public class APIResponse {
    private Map<String, String> response;
}

異常處理程序(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));
    }

響應(與預期不同)

{
    "done": true,
    "cancelled": false,
    "completedExceptionally": false,
    "numberOfDependents": 0
}

異常處理程序(正常)

    @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": {
        "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

public boolean isDone()
public boolean isCancelled()
public boolean isCompletedExceptionally()
public int getNumberOfDependents()

從那時起,方法的名稱是get ,它返回最終的 object, objectmapper只是忽略它

public T get() throws InterruptedException, ExecutionException 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM