Custom error status codes using pattern matching not working

556 Views Asked by At

In my project, I am using serverless. I am trying to change the default statusCodes and response. I have tried the following.

dashboard:
  handler: src/common/dashboard.dashboard
  role: CommonServicesFullAccessRole
  timeout: 30
  events:
    - http:
        integration: lambda
        path: ui/dashboard/
        method: get
        request: 
          parameters: 
            paths: 
              id: true
        response:
          headers:
            Content-Type: "'text/html'"
          template: $input.path('$')
          statusCodes:
            400:
              pattern: '[\s\S]*Bad Request[\s\S]*'
              template: $input.path('$.errorMessage')
              headers:
                Content-Type: "'text/plain'"

In my lambda, I am returning the error callback as

return callback('Bad Request');

Still, I am not able to get the response with the specified statusCode. I am not sure where the exact error is. Following is the response I am getting.

enter image description here

Please help me solve this. Thank you...

1

There are 1 best solutions below

1
On

Try the below.

# Instead of "return callback('Bad Request');"
callback(new Error('Bad Request'));  

Though I am not Node user, I have seen those example codes using Error object in Node.

For Python, I test it if working with your serverless config on the response block.

raise Exception('Bad Request')  # in case of Python

--Edit--

I don't think my serverless.yml has a difference against yours since I just copied the part of yours.

However, I attach my test code, hoping that it would help you.

# serverless.yml

service: "lambda"

provider:
  name: aws
  runtime: nodejs6.10
  region: ap-northeast-2
  stage: test

package:
  exclude:
    - "*/**"
  include:
    - "handler.js"

functions:
  api-test:
    handler: handler.functionOne
    events:
      - http:
          method: get
          path: fire
          integration: lambda

          response:
            headers:
              Content-Type: "'text/html'"
            template: $input.path('$')
            statusCodes:
              400:
                pattern: '[\s\S]*Bad Request[\s\S]*'
                template: $input.path('$.errorMessage')
                headers:
                  Content-Type: "'text/plain'"

# handler.js

module.exports.functionOne = function(event, context, callback) {
    callback(new Error('Bad Request'));
}

# curl

$ curl -X GET https://xxxxxxxx.execute-api.ap-northeast-2.amazonaws.com/test/fire -v
.
.
.
< HTTP/2 400
< content-type: text/plain
< content-length: 11
< date: Mon, 15 Oct 2018 12:40:34 GMT
.
.
.
Bad Request