scala - 如何计算 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 也许我需要使用状态码并且不要使用副作用。但是我能做到的最好的地方是什么?我有很多控制器,不想在每个控制器中拦截它)
我可以在某处全局拦截响应吗?
解决方案
我已经这样做了,希望它会有用
def rejectionHandlerWithCounter: RejectionHandler = { (rejections: Seq[Rejection]) =>
requestInfoEntry.incrementRjectedNum
Some(complete((StatusCodes.Forbidden)))
}
推荐阅读
- javascript - 错误“未捕获的语法错误:输入意外结束”
- python - 两次调用 tf.Session() 导致致命错误:未能获取设备 0 的设备属性 13
- javascript - 根据表单值更新变量
- python-3.x - 无法从 bokeh.themes 导入内置主题的散景
- jenkins - 将 SH 输出转换为数组?
- php - php:组合相同类型的变量值?
- json - 在 json 文档中没有指定键的 bigquery 中从 json 字符串中提取键和值
- r - 如何清理数据库并在 R 中正确读取
- azure-data-explorer - 如何在 Kusto 中创建自定义输出对象
- jhipster - 在没有 uaa 的情况下连接 jhipster 网关