【问题标题】:Custom error status codes using pattern matching not working使用模式匹配的自定义错误状态代码不起作用
【发布时间】:2018-12-07 17:57:46
【问题描述】:

在我的项目中,我使用的是无服务器。我正在尝试更改默认状态代码和响应。我尝试了以下方法。

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'"

在我的 lambda 中,我将错误回调返回为

return callback('Bad Request');

不过,我还是无法获得指定状态码的响应。我不确定确切的错误在哪里。以下是我得到的回应。

请帮我解决这个问题。 谢谢...

【问题讨论】:

    标签: amazon-web-services serverless-framework serverless aws-serverless serverless-framework-offline


    【解决方案1】:

    试试下面的。

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

    虽然我不是Node 用户,但我在Node 中看到了使用Error 对象的示例代码。

    对于Python,如果在response 块上使用您的serverless 配置,我会对其进行测试。

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

    --编辑--

    我不认为我的serverless.yml 和你的有区别,因为我只是复制了你的部分。

    不过,我附上我的测试代码,希望对您有所帮助。

    # 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
    

    【讨论】:

    • 感谢您的回复。尽管如此,它仍然无法正常工作。我想我错过了.yml 文件中的一些配置。您能否检查并告诉我是否遗漏了任何需要定义或提及的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2014-08-01
    相关资源
    最近更新 更多