How to throw custom error from Velocity template using lambda

Viewed 156

In my Lambda I am throwing custom error but from the vtl I am unable to get that when testing in Postman. In the postman I am keep getting message "A custom error was thrown from a mapping template." but I am expecting to get message and object from the custom class like source and errors

Here is my lambda function and custom error file Custom Error file

export class ApiError extends Error {
  source: string
  args: string | undefined
  errors:  [{[key: string]: string | {[key: string]: string}}] | null | string

  constructor(source: string, methodArgs: string, errors: [{[key: string]: string | {[key: string]: string}}] | null | string ) {
    super();
    this.source =  source
    this.args = methodArgs
    this.errors = errors
  }
}


export const completeProcess: Handler = async (event: any): Promise<CustomResponse> => {
  const { customerId } = event.arguments.request as CustomRequest
  if (customerId === null) {
    throw new ApiError("completeProcess", JSON.stringify(event.arguments.request), "customerId missing")
  }
}

Vtl file

request.vtl

{
    "version": "2018-05-29",
    "operation": "Invoke",
    "payload": {
        "field": "getError",
        "arguments":  $utils.toJson($context.arguments)
    }
}

response.vtl

#if($context.error)
  $utils.error($context.result.source, $context.result.errors)
#else
  $utils.toJson($context.result)
#end

When running with above files I am keep getting response as

{
    "data": {
        "completeProcess": null
    },
    "errors": [
        {
            "path": [
                "completeProcess"
            ],
            "data": null,
            "errorType": null,
            "errorInfo": null,
            "locations": [
                {
                    "line": 2,
                    "column": 2,
                    "sourceName": null
                }
            ],
            "message": "A custom error was thrown from a mapping template."
        }
    ]
}
0 Answers
Related