我正在尝试使用 Cask HTTP 框架中的 RawDecorator 来验证 devKey,但我不确定我是否理解当 devKey 无效时如何返回错误响应。这是我正在尝试的:
class AuthenticatedDevKey extends RawDecorator
{
override def wrapFunction(ctx: Request, delegate: Delegate) =
{
// Get the devKey from header
val devKey = ctx.headers.getOrElse("devKey", "").toString
// Check if this is a valid devKey
if(devKey != "" && MicroServiceManager.isExistingDevKey(devKey))
delegate(Map("devKey" -> devKey))
else
cask.Response("Invalid DevKey", statusCode = StatusCodes.UNAUTHORIZED)
}
}
这给了我一个类型不匹配错误。文档(https://com-lihaoyi.github.io/cask/index.html#extending-endpoints-with-decorators)说我可以返回响应,但我还没有看到任何这样的例子。 如何返回带有错误状态代码的响应?
不确定您收到的完整错误消息是什么,但根据提供的示例,我认为您需要返回
Left[cask.Response]
以避免进一步处理,因为您在 Cask - 使用装饰器扩展端点共享的链接中有详细说明
使用装饰器扩展端点
返回
。返回Either[Response, cask.Decor[Any]]
可以让您提前使用固定的Left
退出,避免进一步处理。返回cask.Response
提供参数名称和值的映射,然后将其传递到连续参数列表中的端点函数(如上所示),以及端点终止后运行的可选清理函数。Right
所以,你的代码应该是
class AuthenticatedDevKey extends RawDecorator {
override def wrapFunction(ctx: Request, delegate: Delegate) = {
// Get the devKey from header
val devKey = ctx.headers.getOrElse("devKey", "").toString
// Check if this is a valid devKey
if(devKey != "" && MicroServiceManager.isExistingDevKey(devKey))
delegate(Map("devKey" -> devKey))
else
Left(cask.Response("Invalid DevKey", statusCode = StatusCodes.UNAUTHORIZED))
}
}