【问题标题】:How to create try{ }catch(){ } block with custom message?如何使用自定义消息创建 try{ }catch(){ } 块?
【发布时间】:2022-11-02 15:43:35
【问题描述】:

我的方法看起来像:

public Optional<UserDTO> getUser(String id) {
    if (userRepository.findById(Integer.valueOf(id)).isPresent()) {
        return userRepository.findById(Integer.parseInt(id))
                .map(this::map);
    }
    throw new UserNotFoundException("User wasn't found");
}

但我想用 try{} catch(){} 块来实现它,我试图让它像这样:


public Optional<UserDTO> getUser(String id) {
    try {
        userRepository.findById(Integer.valueOf(id)).isPresent();
        return userRepository.findById(Integer.parseInt(id))
                .map(this::map);
    } catch (UserNotFoundException userNotFoundException){
        var message = "User wasn't found";
        System.out.println(message);
    }
}

但它没有在 id 错误的情况下引发异常,并显示没有返回块的错误。

你能帮我找到可能的解决方案吗?

【问题讨论】:

    标签: java rest exception try-catch


    【解决方案1】:

    它不会抛出异常,因为你的代码中没有任何东西可以抛出,你可以像这样用一行做你想做的事

    userRepository.findById(Integer.valueOf(id)).orElseThrow(() -> new UserNotFoundException("User wasn't found"));
    

    【讨论】:

      【解决方案2】:

      你忘记了 if 部分。

      public Optional<UserDTO> getUser(String id) {
      try {
          if(userRepository.findById(Integer.valueOf(id)).isPresent()){
            return userRepository.findById(Integer.parseInt(id))
                  .map(this::map);
          } else {
            throw new UserNotFoundException();
          }
      } catch (UserNotFoundException userNotFoundException){
          var message = "User wasn't found";
          System.out.println(message);
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        • 2022-12-11
        • 2017-03-14
        • 2013-02-04
        • 1970-01-01
        • 2021-07-04
        相关资源
        最近更新 更多