首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在恢复方法中未处理异常

在恢复方法中未处理异常
EN

Stack Overflow用户
提问于 2020-05-25 18:15:05
回答 1查看 174关注 0票数 0

此方法抛出exception

代码语言:javascript
运行
复制
  @throws(classOf[QuestionNotFoundException])
  def getQuestionFromQuestionID(questionKey: PracticeQuestionKeys) = {
    logger.trace(s"getting question with keys ${questionKey}")
    val practiceQuestionFuture: Future[Option[PracticeQuestion]] = findOne(questionKey)
    for (questionOption <- practiceQuestionFuture) yield {
      questionOption.fold(throw QuestionNotFoundException())(question => {
        logger.trace("got question " + question)
        question
      })
    }
  }

我的用法如下

代码语言:javascript
运行
复制
def function1 = {
...
val res = for{existingQuestion <- questionsRepository.getQuestionFromQuestionID(questionKey){..}
res.recover {
                     case exception => {
                       logger.trace(s"exception ${exception}")
                       Ok(Json.toJson(JsonResultError(messagesApi("error.answerAdditionFail")(langs.availables(0))+". "+exception.getMessage())))
                     }
...
}

我想测试一下function1是否能处理抛出的异常。我写了下面的测试用例

代码语言:javascript
运行
复制
"function" should {
    "should return error if the question id is not correct" in {
      ...

      when(answerTestEnv.mockPracticeQuestionsRepository.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])).thenThrow(
        QuestionNotFoundException()
      )




      val response:Accumulator[ByteString,Result] = controller.function1(request)
      //note that run is how accumulator gets the data and starts processing it. no parameter means no data
      val resultOfAccumulatorRun:Future[Result] = response.run(ByteString(body))
      val responseBody = contentAsJson(resultOfAccumulatorRun)(Timeout(Duration(5000,"millis")),TestEnvImplicits.mat)

      println(s"received response ${responseBody}")
      val result = (responseBody \ "result").get.as[String]

      val additionalInfo = (responseBody \ "additional-info").get.as[String]

      result mustBe "error"
      additionalInfo mustBe components.messagesApi("error.answerAdditionFail")(components.langs.availables(0))+". "+QuestionNotFoundException().msg


    }

}

但是当我运行我的测试用例时,Exception被抛出,但是res.recover似乎不能处理它。我在控制台中看到了这个。

代码语言:javascript
运行
复制
Question not found
utilities.QuestionNotFoundException: Question not found
    at controllers.AnswerController.$anonfun$newAnswer$1(AnswerController.scala:428)

为什么tres.recover`不处理它。

EN

回答 1

Stack Overflow用户

发布于 2020-06-01 17:00:32

传递给recover()的部分函数在失败的Future上被调用,但您的Future不是一个失败的Future,它是一个包含异常作为其“成功”结果类型的Future(实际上它将被强制为更像FutureAnyRef的类型,因为它可以是一个异常或一个PracticeQuestion)。

您可能不想像那样使用Option.fold()。相反,请尝试:

代码语言:javascript
运行
复制
practiceQuestionFuture.flatMap { qOpt =>
          qOpt.map(q => Future(q))
              .getOrElse(Future.failed(QuestionNotFoundException()))
}

(注意:我现在还没有一个编译器来试用它,所以我可能犯了一两个语法错误,但是应该有足够的编译器让你继续)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62000287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档