【问题标题】:Changing response code on request param validation failure with Swagger 2.0使用 Swagger 2.0 更改请求参数验证失败的响应代码
【发布时间】:2014-11-30 23:53:30
【问题描述】:

我在 swagger 之上使用 Apigee 127 创建 REST API。

这是配置文件的头部swagger.yaml

swagger: 2.0
info:
  version: "0.0.1"
  title: LMS API Gateway
# during dev, should point to your local machine
host: localhost
# basePath prefixes all resource paths 
basePath: /
# 
schemes:
  # tip: remove http to make production-grade
  - http
  - https
# format of bodies a client can send (Content-Type)
consumes:
  - application/json
# format of the responses to the client (Accepts)
produces:
  - application/json
x-a127-config: {}
x-volos-resources: {}
paths:
  /lms/oauth2/token:
    # binds a127 app logic to a route
    x-swagger-router-controller: authentication
    x-volos-authorizations: {}
    x-volos-apply: {}
    post:
      description: Authenticates a user
      operationId: authenticate
      parameters:
        - name: body
          in: body
          description: The JSON request body
          required: true
          schema: 
            $ref: AuthenticationRequest
      responses:
        "200":
          description: Success
          schema:
            $ref: AuthenticationResponseSuccess
        default:
          description: Error
          schema:
            $ref: AuthenticationResponseError

然后我有这个AuthenticationRequest Schema Object,它描述了身份验证的请求正文应该是怎样的。到目前为止一切顺利。

当我发出有效请求时,它工作正常,但当我发出无效请求时,我得到以下响应:

HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 60
Date: Mon, 06 Oct 2014 16:31:08 GMT
Connection: keep-alive

Parameter (body) is not a valid AuthenticationRequest model

如果我的 API 规范没有指定我必须为无效请求返回 400 Bad Request 响应代码(顺便说一句更有意义),那将没有问题。 p>

所以问题是我在 Swagger 文档中找不到改变这种行为的方法。

有人吗?

【问题讨论】:

    标签: swagger apigee swagger-tools


    【解决方案1】:

    它现在按设计工作。 swagger-validator 的工作方式是将错误传递给下一个中间件,在这种情况下,如果没有中间件来处理这个问题,你会得到一个 500。 (请参阅swagger-validator.js#L119)以这种方式发生的原因是允许应用程序作者在需要时拦截它。这是故意这样做的,但我可以看到有人可能希望中间件发送响应,但是在内容类型(JSON vs. XML vs. HTML vs. ..)和结构(错误的有效结构是什么?)。

    要让事情按您的意愿工作,您需要添加一个错误处理程序中间件,该中间件将适当地格式化响应及其状态代码。根据您的服务器(连接、快递等),您执行此操作的方式可能会有所改变。

    如果您认为 swagger-tools 应该为此提供便利,请随时提交问题,并提供尽可能多的信息来说明您希望它如何工作。

    【讨论】:

    • 谢谢,我在 swagger-tools 上打开了一个问题。
    • 谢谢恩里克。我在此处发布该问题的链接以供后代使用:github.com/apigee-127/swagger-tools/issues/37
    • 这已在 swagger-tools@0.6.0 中修复。对于那些想知道如何在不破坏 Node.js 中间件协议的情况下解决此问题的人,请查看上面链接的问题。
    • swagger-tools@0.6.0 解决了这个问题。谢谢你,@Jeremy Withlock
    • 你明白了,很高兴我能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2011-09-05
    • 2022-07-23
    • 1970-01-01
    相关资源
    最近更新 更多