【问题标题】:How to throw messages to http response from case class require?如何从案例类要求向http响应抛出消息?
【发布时间】:2016-12-24 05:51:14
【问题描述】:

给定一个带有任何需求的案例类

case class Foo(id: Int, value: Int) {
    require(value < 0 "value must be bigger than zero")
}

可以把这个消息扔到http吗?

val routes = pathPrefix("foos") {
    pathEnd {
      post {
        entity(as[Foo]) { foo =>
          saveFoo(foo) match {
            case Success(p) => {
              complete(StatusCodes.Created)
            }
            case Failure(f) => {
              println(f.getMessage) // unknown error
              complete(BadRequest, f.getMessage)
            }
          }
        }
      }
    } 

【问题讨论】:

    标签: spray akka-http json4s


    【解决方案1】:

    Akka-HTTP 基础架构已经将解组过程中发生的所有错误转换为400 (BadRequest) 错误,并且将自动使用异常消息。

    使用相同的代码,我可以免费获得这种行为。我做了一些小改动:

    • 业务逻辑错误现在是500,以避免混淆

    • 案例类要求现在与消息一致(需要&gt; 而不是&lt;)。


      case class Foo(id: Int, value: Int) {
        require(value > 0, "value must be bigger than zero")
      }
    
      def saveFoo(foo: Foo): Try[Unit] = Success(())
    
      val route = pathPrefix("foos") {
        pathEnd {
          post {
            entity(as[Foo]) { foo =>
              saveFoo(foo) match {
                case Success(p) => {
                  complete(StatusCodes.Created)
                }
                case Failure(f) => {
                  println(f.getMessage) // unknown error
                  complete(StatusCodes.InternalServerError, f.getMessage)
                }
              }
            }
          }
        }
      }
    

    【讨论】:

    • 我也是这么想的。但是来自 f.getMessage 的消息是“未知错误”
    • 如果您的方法saveFoo 返回失败,则会评估您打印f.getMessage 的位置。如果您正在打印f.getMessage,这意味着解组很好,错误在后面。使用 BadRequest 拒绝解组错误发生在幕后,无需添加任何代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多