如何在Scala中返回值或抛出错误

问题描述 投票:0回答:2

我有一个电子邮件列表,每个电子邮件我会在电子邮件表中查找,看看是否存在该电子邮件。如果是的话,别做什么我会抛出错误。这是我的代码;

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]
scala scala-cats
2个回答
1
投票

正如@ 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)
      }
  }

4
投票

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

尝试用map替换flatMap并用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)
          }
      )
© www.soinside.com 2019 - 2024. All rights reserved.