Spray 的 require 错误消息很难看...我该如何自定义?

Spray's require error messages are ugly... how do I customize?

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

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

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

The request content was malformed: Instantiation of [simple type, class com.mycompany.models.users.User$Login] value failed: requirement failed: Invalid email address (through reference chain: com.mycompany.models.users.Login["password"])

我想简单地说

Invalid email address

知道如何完成这个吗?

更新

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

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

我的拒绝处理代码:

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

问题是我想要的消息 ("Invalid zipcode") 被包裹在其他文本中:

cause.detailMessage = "requirement failed: Invalid zipcode"

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

使用 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添加link,它的例子:

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>`
  }
}

同样,我们看到该对象是一个隐式定义,因此您需要将其置于范围内才能被选取。