question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Feature Request: add @ApiException() decorator

See original GitHub issue

I’m submitting a…


[ ] Regression 
[ ] Bug report
[ x ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

no decorator to automate swagger schema generation for HttpException

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: 7.x
Nest swagger: 4.x

Example of implementation

import { HttpException, Type } from '@nestjs/common';
import { ApiResponse, ApiResponseOptions, getSchemaPath } from '@nestjs/swagger';
import { getTypeIsArrayTuple } from '@nestjs/swagger/dist/decorators/helpers';
import { ResponseObject, SchemaObject } from '@nestjs/swagger/dist/interfaces/open-api-spec.interface';

export type Func = () => void;

export interface ApiExceptionOptions extends Omit<ResponseObject, 'description'> {
    description?: string;
    type?: Func | [Func];
    isArray?: boolean;
    schema?: SchemaObject;
}

export const ApiException = <T extends HttpException>(exception: () => Type<T>, options: ApiExceptionOptions = {}): MethodDecorator & ClassDecorator => {
    const instance = new (exception())();

    const apiResponseOptions: ApiResponseOptions = {
        status: instance.getStatus(),
        description: options?.description || instance.message,
        schema: {
            type: 'object',
            properties: {
                statusCode: {
                    type: 'number',
                    example: instance.getStatus(),
                },
                message: {
                    type: 'string',
                },
                error: {
                    type: 'string',
                    example: instance.message,
                },
            },
            required: ['statusCode', 'message'],
        },
    };

    if (options.schema) {
        apiResponseOptions.schema.properties!.message = options.schema;
    } else if (options.type) {
        const [type, isArray] = getTypeIsArrayTuple(options.type, !!options.isArray);
       // For standard data types (Object, String, etc), an error will be shown on the swagger api page, I don't know how to get around it
        apiResponseOptions.schema.properties!.message['$ref'] = getSchemaPath(type!());

        if (isArray) {
            apiResponseOptions.schema.properties!.message = {
                type: 'array',
                items: {
                    type: 'object',
                    $ref: apiResponseOptions.schema.properties!.message['$ref'],
                },
            };
        }
    }

    return ApiResponse(apiResponseOptions);
};

examples

@ApiException(() => NotFoundException)
@ApiException(() => NotFoundException, { description: 'Custom description' })
@ApiException(() => NotFoundException, { description: 'Custom description', schema: { /** custom schema for message prop */} }
@ApiException(() => NotFoundException, { description: 'Custom description', type: () => SomeClassWithSwaggerAnnotitions, isArray: true }

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:17 (9 by maintainers)

github_iconTop GitHub Comments

2reactions
jsproedecommented, Dec 7, 2020

Hi @nartc, sorry that my response took so long. Since your last message to me, I realized that multiple exceptions with the same status code per controller method/route are really an issue. But I’ve found out, that in Swagger UI you can define multiple examples per status code. Over the last few weeks I extended our @ApiException decorator, to be able to handle multiple exceptions with the same status code.

The newest version of our decorator already implements this feature, as you can see in our decorator README.md file. There are still some issues with exception grouping (such as handling multiple exceptions with the same exception name), but I’m currently working on a feature that consecutively numbers the exceptions with the same name as separated examples.

I’ve added some example screenshots and some documentation to the README.md file. I’m hoping that I can finalize the exception-grouping feature before holidays.

What do you think about using examples to show multiple exceptions per status code?

~The grouping feature is already in a feature branch, if you want to take a look at the exception grouping implementation.~

Edit: I’ve just released a new version of our decorator including the exception grouping feature and added some more examples to the documentation.

1reaction
nartccommented, Jul 30, 2020

@ruscon As soon as I have some time this weekend, I’ll implement it. I’ll leave the issue open to keep track though.

Read more comments on GitHub >

github_iconTop Results From Across the Web

ASP.NET Core Web API exception handling - Stack Overflow
Quick and Easy Exception Handling. Simply add this middleware before ASP.NET routing into your middleware registrations. app.UseExceptionHandler(c => c.
Read more >
Exception filters | NestJS - A progressive Node.js framework
The @Catch() decorator may take a single parameter, or a comma-separated list. This lets you set up the filter for several types of...
Read more >
Views - Django REST framework
It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than...
Read more >
How To Handle Errors in a Flask Application - DigitalOcean
Add the following code inside the app.py file: ... You use the @app.route() decorator to create a view function called index() , which...
Read more >
Handling Errors - FastAPI
In this example, when the client requests an item by an ID that doesn't exist, ... You could add a custom exception handler...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found