0

I'm building a response template for an AWS API Gateway endpoint to handle errors. The incoming JSON error message looks like one of the following:

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

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

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

My VTL mapping template looks like:

#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

No matter what input I use to trigger my 400 error response, it falls through to my catch-all else case. The __type that is output in my else case matches one of the other conditionals, so I'm confused why they aren't catching it. Any help would be appreciated! (I'm new to AWS and VTL)

dusk
  • 1,243
  • 1
  • 9
  • 10

2 Answers2

1

Compare strings with equals (constant/not nullable to the left), same as in Java

 #if($unf.equals($type))
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Thanks, this didn't end up being the actual culprit, but was something else I was clearly doing wrong. Will post the answer. – dusk Feb 25 '20 at 20:47
0

Further troubleshooting revealed that VTL treats my constant string variable as a string with no quotes and the JSON object I was pulling from the error message was evaluating to a string with quotes. So my conditional was actually doing this:

#if(UserNotFoundException == "UserNotFoundException")

So I modified how I was setting my constants to be like this:

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

And now the comparison works as expected. Not sure if this is the best way to resolve the issue, but it gets me past this issue.

dusk
  • 1,243
  • 1
  • 9
  • 10