【问题标题】:Handling exceptions from methods in map of Optional处理 Optional 映射中方法的异常
【发布时间】:2018-05-20 23:25:09
【问题描述】:

我有这样的方法。

@Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
    return connector.getConnection(authDTO).map(p->p.getOrders());
}

这里

connector.getConnection(authDTO)

返回一个可选的连接和

p->p.getOrders() 

抛出我无法更改的 KException,其形式为

public class KException extends Throwable {

    // variables
    public String message;
    public int code;

    // constructor that sets the message
    public KException(String message){
        this.message = message;
    }

    // constructor that sets the message and code
    public KException(String message, int code){
        this.message = message;
        this.code = code;
    }
}

这就是 MyException 的结构

public class MyException extends KException {

    public MyException(String message, int code) {
        super(message, code);
    }
}

代码未编译并出现以下错误

unreported exception com.something.exceptions.KException; must be caught or declared to be thrown

我想将此 KException 转换为 MyException。有没有一种优雅的方式来做到这一点?请帮忙。

【问题讨论】:

  • 你为什么不扔KException
  • 只有扩展 MyException 才能转换它。
  • ...你不能扩展KException
  • 将你的return 语句包装在try-catch 中,然后扔掉你需要的任何东西。
  • 返回一个空的Optional&lt;List&lt;Order&gt;&gt;是什么意思?真的会和空的List&lt;Order&gt;有不同的含义吗?您应该避免将集合包装到可选项中(反之亦然),因为这对于调用者来说非常麻烦。

标签: java optional


【解决方案1】:

根据一些 cmets 的建议,您可以在 map 操作中捕获异常,然后执行您需要执行的任何进一步的逻辑:

return getConnection(authDTO).map(p -> {
        try {
            return p.getOrders();
        } catch (KException e) {
            // perform some other logic
        }
});

【讨论】:

  • 根据我对 OP 要求的阅读,Order::getOrders 可能会引发异常。奇怪,但这与可选的或任何结果抛出无关(因为当您从调用 getOrders 中抛出时,另一个异常已经被抛出)。
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 2015-05-21
  • 2018-08-19
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 2013-01-14
相关资源
最近更新 更多