【问题标题】:Throw exception when DomainClassConverter can't find entity with @PathVariable当 DomainClassConverter 找不到带有 @PathVariable 的实体时抛出异常
【发布时间】:2017-01-10 13:40:52
【问题描述】:

例如:

@RestController
@RequestMapping("/item")
class ItemController {

    @RequestMapping(value = "/{id}", method = GET)
    Item get(@PathVariable("id") Item item) {
        return item;
    }
}

我不想每次在某些记录不存在时处理 DomainClassConverter 返回 null 的情况。我希望自动抛出异常。有可能吗?

【问题讨论】:

    标签: spring-mvc spring-data


    【解决方案1】:

    是的,检查是否没有找到项目引发自定义异常。

    class ItemNotFoundException extends Exception{  
           ItemNotFoundException(String s){  
          super(s);  
         }  
      } 
    

    并像这样更改您的代码并根据您的需要处理异常。

    @RestController
    @RequestMapping("/item")
    class ItemController {
    
        @RequestMapping(value = "/{id}", method = GET)
        Item get(@PathVariable("id") Item item) {
            if(item ==null){
                throw new ItemNotFoundException("No item found.");  
            }else{
                return item;
            }
        }
    }
    

    【讨论】:

    • 这是我想要避免的,我想自动处理它。事实上,我已经解决了这个问题,但我的解决方案似乎有点奇怪。所以我想知道是否还有其他我不知道的方法。
    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多