Handling exceptions while returning values by Optional flatmap

给你一囗甜甜゛ 提交于 2020-01-06 05:15:08

问题


I have tried implementing Optional from JAVA in the below code. getOrders() method throws a KException.

    @Override
    public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
        List<Order> orders=null;
        try {
            Optional<KConnect> connection = connector.getConnection(authDTO);
            if (connection.isPresent()) {
                orders = connection.get().getOrders();
            }
        }catch (KException e){
            throw new MyException(e.message,e.code);
        }
        return Optional.ofNullable(orders);
    }

I tried to remove the isPresent() check and replace it with flatmap.

    @Override
    public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
        return connector.getConnection(authDTO).map(p -> {
            try {
                return p.getOrders();
            } catch (KException e) {
                throw new MyException(e.message,e.code); // [EXP LINE]
            }
        });
    }

In this case I am not able to catch KException and convert it to MyException. My code won't compile.

unreported exception com.myproject.exception.MyException; must be caught or declared to be thrown

1st snippet works perfectly fine for me. Is there a better way to do this? Please suggest.

Edit: This does not change if I make it map instead of flatmap. The exact problem is that IntelliJ is saying unhandled exception: com.myproject.exception.MyException at [EXP LINE] even though the method has throws MyExpception present.

来源:https://stackoverflow.com/questions/47661370/handling-exceptions-while-returning-values-by-optional-flatmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!