簡體   English   中英

Spring GetMapping注釋異常

[英]Spring GetMapping annotation exception

控制器類中有以下方法:

    @GetMapping("{id:" + REGEXP + "}")
    @ResponseBody
    public SomeObject getById(@PathVariable UUID id) {
        return someObjectService.getById(id));
    }

REGEXP是一個簡單的正則表達式字符串。 在someObjectService中,getById方法處理無法通過id找到對象並引發異常的情況。 對於此類情況,還有異常處理程序類可自定義錯誤響應:

    @ExceptionHandler({ResourceNotFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public CustomErrorResponse handleNotFoundCase (ResourceNotFoundException exception) {
        CustomErrorResponse customerErrorResponse = new CustomErrorResponse();
        // filling CustomErrorResponse with specific data using 'exception'
        return customerErrorResponse;
    }

因此,當我使用一些不存在的id測試getById並通過REGEXP檢查時,預期結果=實現結果:404和錯誤的json主體具有CustomErrorResponse的結構(來自處理程序)。

但是,當我對id進行相同操作時,它不通過REGEXP檢查-404發生,但錯誤的json主體為默認值(bootstrap),它沒有CustomErrorResponse結構。

問題是:當@GetMapping("{id:" + REGEXP + "}")中的@GetMapping("{id:" + REGEXP + "}")未通過正則表達式檢查時,會引發什么類型的異常?在哪里(進行進一步的適當處理)?

為什么要嘗試在您的get映射中發布json? 在這種情況下,您將需要使用localhost:8080 / yourApp / entity / {id:10}而不是localhost:8080 / yourApp / entity / 10實際需要的嗎?

請查看此頁面,了解如何設計REST端點: https : //docs.microsoft.com/en-us/azure/architecture/best-practices/api-design

關於您的問題-在這種情況下,您不能使用驗證。 您需要為此字段添加自定義驗證器。請在此處找到“自定義驗證器”部分: https : //www.mkyong.com/spring-boot/spring-rest-validation-example/

如果要創建正則表達式以檢查uuid是否正確,則不需要這樣做,並且

@GetMapping("/{id}")
public SomeObject getById(@PathVariable UUID id) {

將驗證這一點。

另一方面,如果您對此有更嚴格的要求,而不是需要使用模式驗證器:

@RestController
@Validated
public class Ctrl {
    // ...
    @GetMapping("/{id}")
    public String getById(@Pattern(regexp = REGEXP) @PathVariable String id) {
        return someObjectService.getById(UUID.fromString(id)));
    }

}

請注意,模式驗證器不適用於UUID類型,因此您必須手動將String轉換為UUID。

您可以在https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html中閱讀有關驗證的更多信息。

暫無
暫無

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

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