首页 > 解决方案 > 如何计算 akkaHttp RejectionHandler 拒绝和成功?

问题描述

我正在尝试计算 RejectionHandler 返回的拒绝我想我现在这样做的方式不是最好的,甚至是不正确的。我只是试图在我的数据库中调用增量方法,在每个处理的情况下。

  implicit def rejectionHandler: RejectionHandler =
    RejectionHandler.newBuilder()
      .handle {
        case MissingCookieRejection(cookieName) =>
          requestInfoEntry.incrementRjectedNum
          complete(HttpResponse(BadRequest, entity = "No cookies, no service!!!"))
      }
      .handle {
        case AuthorizationFailedRejection =>
          requestInfoEntry.incrementRjectedNum
          complete((Forbidden, "You're out of your depth!"))
      }
      .handle {
        case ValidationRejection(msg, _) =>
          requestInfoEntry.incrementRjectedNum
          complete((InternalServerError, "That wasn't valid! " + msg))
      }
      .handleAll[MethodRejection] { methodRejections =>
        requestInfoEntry.incrementRjectedNum//todo sideeffect ??
        val names = methodRejections.map(_.supported.name)
        complete((MethodNotAllowed, s"Can't do that! Supported: ${names mkString " or "}!"))
      }
      .handleNotFound {
        requestInfoEntry.incrementRjectedNum
        complete((NotFound, "Not here bldghad!"))
      }
      .result()

当我“访问我未找到的页面”时,Akka HTTP 向我返回了一个正确的响应:“不在这里 bldghad!” 每次我在不存在的网页上刷新浏览器时。但是当我检查我的数据库时,我看到了唯一的一个增量。我可以像我一样这样做吗?(我也需要计算成功)

PS 也许我需要使用状态码并且不要使用副作用。但是我能做到的最好的地方是什么?我有很多控制器,不想在每个控制器中拦截它)

我可以在某处全局拦截响应吗?

标签: scalaakka

解决方案


我已经这样做了,希望它会有用

  def rejectionHandlerWithCounter: RejectionHandler = { (rejections: Seq[Rejection]) =>
    requestInfoEntry.incrementRjectedNum
    Some(complete((StatusCodes.Forbidden)))
  }

推荐阅读