swagger - 使用 Swagger 2.0 更改请求参数验证失败时的响应代码

标签 swagger apigee swagger-tools

我在 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 对象,它描述了身份验证的请求正文应该如何。到目前为止一切顺利。

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

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 响应代码(顺便说一句,更有意义)。

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

有人吗?

最佳答案

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

为了让事情按照您想要的方式工作,您需要添加一个错误处理程序中间件,该中间件将适本地格式化响应及其状态代码。根据您的服务器(连接、快速等),您的操作方式可能会有所不同。

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

关于swagger - 使用 Swagger 2.0 更改请求参数验证失败时的响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26221020/

相关文章:

c# - 如何使用 Swagger 生成选项(CORS)

node.js - 如何将 swagger-ui npm 模块与现有的 OpenAPI 规范文件一起使用

javascript - Apigee 用户网格 : Mass delete option missing

node.js - 当传入的客户端 http 请求终止时终止传出的 http 请求

swagger - 代码生成默认初始化为空列表而不是空

c# - ServiceStack + Swagger 以不同方式对资源进行分组的能力

node.js - 通过用户网格身份验证防止共享 session

google-cloud-platform - StackDriver支持Syslog协议(protocol)吗?

swagger - "discriminator"多态性,OpenAPI 2.0 (Swagger 2.0)