【问题标题】:Why is my Velocity Template Language conditional not working?为什么我的 Velocity 模板语言条件不起作用?
【发布时间】:2020-06-09 13:36:54
【问题描述】:

我正在为 AWS API Gateway 端点构建一个响应模板来处理错误。传入的 JSON 错误消息类似于以下内容之一:

{
    "__type": "UserNotFoundException",
    "message": "User does not exist."
}

{
    "__type": "NotAuthorizedException",
    "message": "Incorrect username or password."
}

{
    "__type": "NotAuthorizedException",
    "message": "Password attempts exceeded"
}

我的 VTL 映射模板如下所示:

#set($inputRoot = $input.path('$'))
#set($unf = "UserNotFoundException")
#set($nae = "NotAuthorizedException")
#set($type =$input.json('$.__type'))

#if($type == $unf)
{
  "__type": "UserNotFoundException",
  "message": $input.json('$.message'),
  "referenceCode": "UNF0000"
}
#elseif($type == $nae)
{
  "__type": "NotAuthorizedException",
  "message": $input.json('$.message'),
  "referenceCode": "NAE0000"
}
#else
{
  "__type": $input.json('$.__type'),
  "message": $input.json('$.message'),
  "referenceCode": "FAIL0000"
}
#end

无论我使用什么输入来触发我的 400 错误响应,它都属于我的万能情况。在我的 else 案例中输出的 __type 与其他条件之一匹配,所以我很困惑为什么他们没有抓住它。任何帮助,将不胜感激! (我是 AWS 和 VTL 的新手)

【问题讨论】:

    标签: json aws-api-gateway velocity


    【解决方案1】:

    将字符串与equals(左侧常量/不可为空)比较,与Java中相同

     #if($unf.equals($type))
    

    【讨论】:

    • 谢谢,这并没有成为真正的罪魁祸首,但我显然做错了其他事情。将发布答案。
    【解决方案2】:

    进一步的故障排除显示,VTL 将我的常量字符串变量视为不带引号的字符串,并且我从错误消息中提取的 JSON 对象正在评估为带引号的字符串。所以我的条件实际上是这样做的:

    #if(UserNotFoundException == "UserNotFoundException")
    

    所以我修改了我设置常量的方式:

    #set($unf  = '"UserNotFoundException"')
    #set($nae  = '"NotAuthorizedException"')
    

    现在比较可以按预期进行。不确定这是否是解决问题的最佳方法,但它让我解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2011-12-20
      • 2013-06-07
      • 2019-03-07
      • 2018-07-21
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多