scottie1984 / swagger-ui-express

Adds middleware to your express app to serve the Swagger UI bound to your Swagger document. This acts as living documentation for your API hosted from within your app.
MIT License
1.42k stars 225 forks source link

Error handling middleware not working #233

Closed jinnatul closed 2 years ago

jinnatul commented 3 years ago

Swagger config

import swaggerJsDoc from 'swagger-jsdoc';

const swaggerOptions = {
  swaggerDefinition: {
    info: {
      version: '1.0.0',
      title: 'eCommerce',
      description: 'Application Programming Interface for eCommerce application.',
      contact: {
        name: '@TeamTigers',
      },
      servers: ['http://localhost:4000', 'https://bideshi.herokuapp.com/'],
    },
    securityDefinitions: {
      jwt: {
        type: 'apiKey',
        name: 'Authorization',
        in: 'header',
      },
    },
    security: [
      {
        jwt: [],
      },
    ],
  },
  apis: [
    './src/router/router.js',
  ],
};

const swaggerDocs = swaggerJsDoc(swaggerOptions);

export default swaggerDocs;

app.js

app.use('/', swaggerUI.serve, swaggerUI.setup(swaggerDocs));

app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

When I visit this route http://localhost:4000/ then I show swagger UI like this. Screenshot

But, when I visit an anonymous route like http://localhost:4000/api/data then I got this error. a1

when i hide this line // app.use('/', swaggerUI.serve, swaggerUI.setup(swaggerDocs)); then i got my custom error message a2

So, how to way I can solve this problem?

scottie1984 commented 3 years ago

Recommendation is to place the swagger routes under /docs or something else as to not interfere with your application routes

jinnatul commented 3 years ago

@scottie1984, Thanks for your response.

Now it's working but when I visit /docs/somthing then still i got this error. https://user-images.githubusercontent.com/31995155/102715757-bd9ad000-4301-11eb-839d-49f3ad3c9f07.png

scottie1984 commented 2 years ago

Instead of

app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs));

you could use

app.use('/api-docs', swaggerUI.serve)
app.get('/api-docs', swaggerUI.setup(swaggerDocs));