问题描述
我正在处理一个 swagger 2.0 文件,我想在其中指定响应中的错误代码只能是 USERNAME_VALIDATION_FAILED 或 EMAIL_VALIDATION_FAILED.这是由于 swaggerfile 的 swagger-ui 视图,其中每个响应错误都可以在错误代码枚举中定义 20 个错误代码.如何限制特定响应的可能错误代码?
There is a swagger 2.0 file I am dealing with, where I want to specify that the error code from my response can only be USERNAME_VALIDATION_FAILED or EMAIL_VALIDATION_FAILED. This is due to a swagger-ui view of the swaggerfile where every response error can have the 20 error codes defined in the Error code enum.How to limit the possible error codes for a specific response?
在我的 swaggerfile 中有请求
In my swaggerfile there is the request
/register:
post:
...
parameters:
...
responses:
...
400:
description: Username or email validation failed, possible values for code are USERNAME_VALIDATION_FAILED, EMAIL_VALIDATION_FAILED
schema:
$ref: '#/definitions/Error'
我的错误看起来像
Error:
type: object
properties:
code:
type: string
enum:
- USERNAME_VALIDATION_FAILED
- EMAIL_VALIDATION_FAILED
- USERNAME_EXISTS
- ...
我会建议类似的东西
schema:
$ref: '#/definitions/Error.code.of(USERNAME_VALIDATION_FAILED, EMAIL_VALIDATION_FAILED)'
推荐答案
您无法覆盖属性的 enum
,因此您需要一个单独的模型:
You can't override the enum
of a property, so you need a separate model:
RegistrationError:
type: object
properties:
code:
type: string
enum:
- USERNAME_VALIDATION_FAILED
- EMAIL_VALIDATION_FAILED
Error:
type: object
properties:
code:
type: string
enum:
- USERNAME_VALIDATION_FAILED
- EMAIL_VALIDATION_FAILED
- USERNAME_EXISTS
- ...
如果错误模型具有共同的属性,您可以从基础模型继承"它们以减少代码重复:
If the error models have common properties, you can "inherit" them from a base model to reduce code duplication:
BaseError:
type: object
properties:
message:
type: string
RegistrationError:
allOf:
- $ref: "#/definitions/BaseError"
- type: object
properties:
code:
type: string
enum:
- USERNAME_VALIDATION_FAILED
- EMAIL_VALIDATION_FAILED
Error:
allOf:
- $ref: "#/definitions/BaseError"
- type: object
properties:
code:
type: string
enum:
- USERNAME_VALIDATION_FAILED
- EMAIL_VALIDATION_FAILED
- USERNAME_EXISTS
- ...
这篇关于招摇限制响应的错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!