如何在Scala中返回值或丢弃错误



我都有一个电子邮件列表,对于每个电子邮件,我将在电子邮件表中查找它,以查看该电子邮件是否存在。如果这样做,什么也不做,我会丢下错误。这是我的代码;

def lookupEmailStatus(email: EmailAddress, requestId: RequestId)(
      implicit ec: ExecutionContext): HttpServiceResult[List[EmailStatusDTO]] = {
    emailDatabase
      .getEmailStatusByEmail(email, requestId)
      .map(
        l =>
        if (l.isEmpty) {
          logger.error(
            LoggingMessage(
              requestId,
              s"Email status not found by ${email.email} failed"))
          EntityNotFound(s"${email.email}", requestId)
        } else {
          l
        }
      )
      .leftMap[HttpError] {
        case e =>
          logger.error(
            LoggingMessage(
              requestId,
              s"Retrieve email status by ${email.email} failed"))
          DatabaseError(e.message, requestId)
      }
  }

我运行代码时会出现错误:

Error:(57, 27) type mismatch;
 found   : cats.data.EitherT[model.HttpError,Product with Serializable]
 required: model.HttpServiceResult[List[EmailStatusDTO]]
    (which expands to)  cats.data.EitherT[model.HttpError,List[EmailStatusDTO]]
      .leftMap[HttpError] {

如果我删除了.map(..)方法,它可以正常工作,但这不是我想要的:

def lookupEmailStatus(email: EmailAddress, requestId: RequestId)(
          implicit ec: ExecutionContext): HttpServiceResult[List[EmailStatusDTO]] = {
        emailDatabase
          .getEmailStatusByEmail(email, requestId)
          .leftMap[HttpError] {
            case e =>
              logger.error(
                LoggingMessage(
                  requestId,
                  s"Retrieve email status by ${email.email} failed"))
              DatabaseError(e.message, requestId)
          }
      }

这是类型定义:

type HttpServiceResult[A] = ServiceResult[HttpError, A]
type ServiceResult[Err, A] = EitherT[Future, Err, A]

如果if的一个分支返回列表,而另一个分支将返回错误,则if完全返回Product with Serializable

尝试用flatMap替换map,并用EitherT

将分支的包装结果替换
def lookupEmailStatus(email: EmailAddress, requestId: RequestId)(
    implicit ec: ExecutionContext): HttpServiceResult[List[EmailStatusDTO]] = 
    emailDatabase
      .getEmailStatusByEmail(email, requestId)
      .leftMap[HttpError] {
        case e =>
          logger.error(
            LoggingMessage(
              requestId,
              s"Retrieve email status by ${email.email} failed"))
          DatabaseError(e.message, requestId)
      }.flatMap[HttpError, List[EmailStatusDTO]](
        /*(*/l/*: List[EmailStatusDTO])*/ =>
          if (l.isEmpty) {
            logger.error(
              LoggingMessage(
                requestId,
                s"Email status not found by ${email.email} failed"))
            EitherT.leftT/*[Future, List[EmailStatusDTO]]*/(EntityNotFound(s"${email.email}", requestId))
          } else {
            EitherT.rightT/*[Future, HttpError]*/(l)
          }
      )

如已经提到的 @dmytro-mitin,问题的根本原因是您在条件的两个分支中都没有返回相同的类型。解决的一种方法是确保您返回正确的类型。

我认为,更好的方法是将cats.data.EitherT.ensure用于list.isEmpty检查。这样,您就会明确您关心的内容(即,如果列表为空,返回错误),而不必手动处理快乐案件。

您的代码将变成:

def lookupEmailStatus(email: EmailAddress, requestId: RequestId)(
      implicit ec: ExecutionContext): HttpServiceResult[List[EmailStatusDTO]] = {
    emailDatabase
      .getEmailStatusByEmail(email, requestId)
      .ensure({
         logger.error(LoggingMessage(requestId, s"Email status not found by ${email.email} failed"))}
         EntityNotFound(s"${email.email}", requestId)
      })(!_.isEmpty)
      .leftMap[HttpError] {
        case e =>
          logger.error(
            LoggingMessage(
              requestId,
              s"Retrieve email status by ${email.email} failed"))
          DatabaseError(e.message, requestId)
      }
  }

最新更新