如何在TSOA中为同一状态码配置多个错误响应或添加示例错误?
I get exactly what you're dealing with—TSOA's @Response decorator does overwrite earlier definitions for the same status code since it uses the status code as a key under the hood. Let's break down your two practical options here:
Option 1: Add Multiple Error Examples to a Single 409 Response
If your main goal is to display different 409 error scenarios in the Swagger UI (via the "examples" dropdown you mentioned), you don't need multiple @Response decorators. Instead, bundle all your error examples into one @Response using the examples configuration option.
Here's how to adjust your code:
@Response<ErrorBody>('409', 'Conflict Errors', { examples: { "Error Scenario 1": { value: { type: 'https://someurl.com', status: 409, code: 'error/409-error-one', title: 'This is an example', detail: 'You should provide error detail', } }, "Error Scenario Fred": { value: { type: 'https://someurl.com', status: 409, code: 'error/409-error-one-hundred-and-fifty', title: 'This is an example of another error', detail: 'You should provide error detail for all errors', } } } })
This will generate an OpenAPI spec where the 409 response includes both examples, and they'll show up as separate options in the Swagger editor's examples dropdown—exactly what you're looking for.
Option 2: Define Multiple Schemas for the Same Status Code (Advanced)
If you actually need distinct schemas for your two 409 errors (not just different example values), TSOA's built-in @Response decorator doesn't support this out of the box. But you can use the @OpenApi decorator to manually extend the OpenAPI spec with a oneOf structure for the response:
@OpenApi({ responses: { '409': { description: 'Conflict Errors', content: { 'application/json': { schema: { oneOf: [ { $ref: '#/components/schemas/ErrorBody' }, // Replace with a second distinct schema reference if needed { $ref: '#/components/schemas/ErrorBody' } ] }, // You can still attach examples here if required examples: { // ... your example objects } } } } } })
Note that if both errors use the same ErrorBody schema, the first option (adding examples) is cleaner and more aligned with OpenAPI best practices. Only use this oneOf approach if the two 409 responses have structurally different payloads.
Quick Note on Your Current Code
Your existing dual @Response decorators work fine for throwing errors in your application logic, but as you noticed, TSOA will only retain the last one in the generated spec. Swapping to either of the above approaches will fix the documentation gap while keeping your error-throwing behavior intact.
内容的提问来源于stack exchange,提问作者supertux

