【问题标题】:Spray's require error messages are ugly... how do I customize?Spray 的 require 错误消息很难看……我该如何自定义?
【发布时间】:2015-09-02 23:42:13
【问题描述】:

我正在使用 Spray 编写一个 Web 应用程序,并且正在使用本文底部描述的案例类验证方法:

http://spray.io/documentation/1.2.3/spray-routing/advanced-topics/case-class-extraction/

效果很好,但我对返回给客户端的消息不满意。除了丑之外,它还暴露了一些关于后端的细节:

请求内容格式错误: [simple type, class com.mycompany.models.users.User$Login] 值的实例化失败:要求 失败:无效的电子邮件地址(通过引用链: com.mycompany.models.users.Login["password"])

我想说,简单

电子邮件地址无效

你知道如何做到这一点吗?

更新

我已经实现了@soong 的建议,但效果很好(到目前为止)。

我的要求代码是require(!zipcode.isEmpty, "Invalid zipcode")

我的拒绝处理程序代码:

  implicit def validationRejectionHandler = RejectionHandler {
    case MalformedRequestContentRejection(msg, cause) :: _ =>
      complete(BadRequest, s"$msg")
  }

问题是我想要的消息(“无效的邮政编码”)包含在其他一些文本中:

cause.detailMessage = "requirement failed: Invalid zipcode"

有什么方法可以在不进行字符串操作的情况下获得我的确切错误消息?

【问题讨论】:

标签: scala jackson spray


【解决方案1】:

使用 Spray,您可以通过自定义异常处理程序来做到这一点。以下是来自their page describing it 的示例:

import spray.util.LoggingContext
import spray.http.StatusCodes._
import spray.routing._

implicit def myExceptionHandler(implicit log: LoggingContext) =
  ExceptionHandler {
    case e: ArithmeticException =>
      requestUri { uri =>
        log.warning("Request to {} could not be handled normally", uri)
        complete(InternalServerError, "Bad numbers, bad result!!!")
      }
  }

class MyService extends HttpServiceActor {
  def receive = runRoute {
    `<my-route-definition>`
  }
}

请注意,它是一个隐式定义,因此当您定义服务时,您需要做的就是将其置于范围内,然后它将被拾取。它未处理的任何错误都将默认为其原始值。与大多数异常处理情况一样,我鼓励您在决定处理哪些异常时非常具体。

既然你说的其实是拒绝,而不是例外,那我就加上rejection handling的链接,及其例子:

import spray.routing._
import spray.http._
import StatusCodes._
import Directives._

implicit val myRejectionHandler = RejectionHandler {
  case MissingCookieRejection(cookieName) :: _ =>
    complete(BadRequest, "No cookies, no service!!!")
}

class MyService extends HttpServiceActor {
  def receive = runRoute {
    `<my-route-definition>`
  }
}

再一次,我们看到对象是一个隐式定义,因此您需要将它放在被拾取的范围内。

【讨论】:

  • 很高兴我能帮上忙!我在尝试测试基于 Spray 的 API 时第一次遇到这些问题,我不知道我需要单元测试范围内的处理程序来验证路由。 花了我一段时间才弄明白!
  • 其实,我说得太早了……效果不太好。我在上面编辑了我的问题。想法?
猜你喜欢
  • 1970-01-01
  • 2012-05-05
  • 2020-12-05
  • 1970-01-01
  • 2017-02-24
  • 2018-08-08
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多