处理可选地图中方法的异常

时间:2017-12-06 23:22:20

标签: java optional

我有这样的方法。

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

这里

connector.getConnection(authDTO)

返回Connection的可选项和

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。是否有一种优雅的方式来做到这一点?请帮助。

1 个答案:

答案 0 :(得分:0)

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

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