【问题标题】:Spring boot endpoint parameter signature, is throwing ambiguous endpoint exception when both parameters are givenSpring Boot端点参数签名,当同时给出两个参数时抛出不明确的端点异常
【发布时间】:2019-07-02 14:59:36
【问题描述】:

由于过去的设计方式,在这种情况下,为名为@9​​87654321@ 的特定参数创建了一个端点。

但是,该要求意味着端点可以与foo 或称为bobby 的新参数一起使用。

在尝试整合到一个端点之后,重构工作太多了。

所以我选择重载端点并使用 spring boot 技巧让签名由请求参数决定。

像这样:

@GetMapping(params = {"foo"})
    public CollectionResource<FooResource> get(@RequestParam("foo") String foo, ...) {} ...

@GetMapping(params = {"bobby"})
    public CollectionResource<FooResource> get(@RequestParam("bobby") {} ...

这样在与端点交互时效果很好:

localhost:8080/testEndpoint?foo=bar

localhost:8080/testEndpoint?bobby=tables

但是,我在尝试以下操作时发现了一个极端情况:

localhost:8080/testEndpoint?bobby=tables&foo=bar

这会引发以下运行时异常

java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/testEndpoint/':

此端点不是由用户点击而是以编程方式命中,因此这种情况发生的可能性非常小。但是,有没有办法设置控制器,以便它可以处理这个问题并抛出一个 BadRequest 等而不是炸毁?

Spring Boot 版本1.5.16.RELEASE

【问题讨论】:

    标签: java spring spring-boot spring-restcontroller ambiguous


    【解决方案1】:

    为什么不选择主要终点?

    首先,只需添加附加参数即可

     public CollectionResource<FooResource> get(@RequestParam("foo") String foo, ...
      ,@RequestParam("bobby")) {
    

    在这种极端情况下,将选择第一个端点

    【讨论】:

      【解决方案2】:

      Spring 无法根据 Request 参数区分端点。

      代替两个端点来服务两个请求参数,只有一个端点和两个请求参数。您可以选择将其设为不需要。

      @RequestParam("foo") String foo required = false, @RequestParam("bobby") String foo required = false
      

      这为您提供了更简单的 API 处理方式

      【讨论】:

        【解决方案3】:

        尝试使用异常处理程序

         @ExceptionHandler(Exception.class)
            public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
                List<String> details = new ArrayList<>();
                details.add(ex.getLocalizedMessage());
                ErrorResponse error = new ErrorResponse("Server Error", details);
                return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
            }
        

        【讨论】:

        • 这似乎很危险,这不会掩盖所有 500 个错误,不管其根本原因是什么?
        • 您必须记录所有错误并在需要时添加修复程序。抛出服务未定义异常并不好......
        猜你喜欢
        • 2020-09-05
        • 2019-05-20
        • 2023-02-02
        • 2018-10-19
        • 1970-01-01
        • 2014-02-17
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        相关资源
        最近更新 更多