簡體   English   中英

Spring JSON 解析錯誤后啟動人類可讀錯誤消息

[英]Spring Boot human readable error messages after JSON parsing error

我有一個 REST API 使用 Spring 引導編寫。 現在我想加強錯誤處理。 如果用戶發送無效的 JSON 或 JSON 無法反序列化到我的 DTO,我會通知用戶究竟出了什么問題,例如意外的屬性名稱、類型等。我仍然不想公開有關實現的任何信息(例如堆棧跟蹤,class 名稱)。

默認 Spring 實現返回

InvalidFormatException: Cannot deserialize value of type `java.lang.Integer` from String \"aaa\": not a valid Integer value\n at [Source: (PushbackInputStream); line: 10, column: 19]
 (through reference chain: com.yell.statementofwork.model.StatementOfWorkCompletionDtoSe[\"purchasedProducts\"]->java.util.ArrayList[0]->com.yell.statementofwork.model.PurchasedProductDtoSe[\"quantity\"])",

這幾乎很好,但我更願意從中刪除有關 class 的信息。 你有什么建議嗎?

您可以創建自己的自定義 ConstraintValidator 並使用相應的注釋注釋您的 DTO object

您可以在此處找到示例 - http://dolszewski.com/spring/custom-validation-annotation-in-spring/

PS該示例對一個字段使用注釋,但您可以在整個 class 上使用它

在 spring 引導 REST API 中處理不同類型錯誤的最簡單方法是使用 Z2A2D4F065E6BED93B01B3D4F277P。 首先,讓我們創建一個自定義異常 class

public class InvalidFormatException extends RuntimeException {

    private final String message;
    private final List<String> data;

    // getters , setters and constructors
}

然后創建一個錯誤響應 model class。 這個 model class 將提供一個 JSON 結構,說明在發生異常時應該發回給用戶的內容

public class ErrorResponseModel {
    
    String code;
    String type;
    String message;
    List<String> data;

    // getters, setters, and constructor
}

然后使用 spring AOP 為您的 controller 創建一個自定義異常處理程序

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(InvalidFormatException.class)
    public ResponseEntity<ErrorResponseModel> badRequestException(InvalidFormatException ex, WebRequest request) {
        return new ResponseEntity<>(new ErrorResponseModel(ex.getMessage(), ex.getData()),
                HttpStatus.BAD_REQUEST);
    }
}

您可以在此 class 中添加和處理更多類似的錯誤類型。 現在,每當您拋出異常時,它都會在此處被攔截,並將自定義錯誤響應發送回用戶。

暫無
暫無

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

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