如何在stream().map()中抛出并且捕获自定义异常

以下是一个xxxServiceImpl类的代码示例

public PagedList<DeviceOnlineLog> getAll(int page, int pageSize,String queryStr,LocalDateTime from,LocalDateTime to){
  List<DeviceOnlineLogEntity>logEntities=null;
  List<DeviceOnlineLog>list=null;
  if(from == null || to == null){
    from = LocalDateTime.of(2000,1,1,0,0);
    to = LocalDateTime.now();
  }
  logEntities =
    logRepository.findBetweenTime(Timestamp.valueOf(from), Timestamp.valueOf(to));
  list=logEntities.stream().map(p->{
    DeviceOnlineLog deviceLog = new DeviceOnlineLog();
    deviceLog.setLastTime(p.getLastTime());
    deviceLog.setIsOnline(p.getIsOnline());
    DeviceDetailEntity detailEntity;
    try{
      if (queryStr.equals("")) {
        detailEntity = deviceRepository.getOne(p.getDeviceId());
      } 
      else {
        detailEntity =
          deviceRepository.findByNameOrDescription(queryStr,
                                                   p.getDeviceId());
       }
       if(detailEntity==null){
          throw new DeviceException("输入的参数不合法,无法查询到相关的设备详情上下线日志信息");//如果查询的结果为空,则在此处抛出异常
                }
                deviceLog.setDeviceName(detailEntity.getName());
      deviceLog.setDescription(detailEntity.getDescription());
            }
            catch (DeviceException e){
                e.printStackTrace();//在此处捕获异常
            }
            return deviceLog;
        }).collect(Collectors.toList());

        PagedList<DeviceOnlineLog> deviceLogPagedList=new PagedList<>(logEntities.size(),page,pageSize);
        deviceLogPagedList.setItems(list);
        return deviceLogPagedList;
    }

这里的DeviceException是一个自定义的异常类:

package com.siid.webapi.device.controller;

public class DeviceException extends Exception {
    public DeviceException(){}

    public DeviceException(String s){
        super(s);
    }
}
发布了51 篇原创文章 · 获赞 0 · 访问量 740

猜你喜欢

转载自blog.csdn.net/lxy1740/article/details/104307276