How do I add an express middleware function to a swagger node project?

Not applicable

How do I add an express middleware function to a swagger node project ?

In case I want to do some custom error handling in code , I am writing a middleware like this,

app.use(function(err, req, res, next) {

console.error("inside error middleware");

res.status(500).send('Something broke!'); });

The function is not behaving as I expect an express middleware to work.What is the best way to add middlewares to swagger-node projects.

Solved Solved
0 3 1,509
1 ACCEPTED SOLUTION

Not applicable

@Hemanth Shetty and @Srinandan Sridhar, have you considered swagger-tools ? I use it extensively on my projects and runs pretty smoothly. The definition of routes is slightly than in swagger-node. Both great frameworks. Sorry that it doesn't address the question directly.

Here's a snippet of my code handling errors:

// Validate Swagger requests  app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller  

app.use(middleware.swaggerRouter(options));

// error handler
// no stacktraces leaked to user unless in development environment
app.use(function (err, req, res, next) {
  "use strict";
  utils.sendError(err.status || err.code || 500, err, req, res);
});

Hope it helps!

View solution in original post

3 REPLIES 3

Former Community Member
Not applicable

@kevinswiber or @Scott Ganyo - can either of you please help?

Not applicable

I don't think I have enough information because I just tried doing that and it worked fine.

One possible gotcha: Be sure you call next() in your controllers.

Not applicable

@Hemanth Shetty and @Srinandan Sridhar, have you considered swagger-tools ? I use it extensively on my projects and runs pretty smoothly. The definition of routes is slightly than in swagger-node. Both great frameworks. Sorry that it doesn't address the question directly.

Here's a snippet of my code handling errors:

// Validate Swagger requests  app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller  

app.use(middleware.swaggerRouter(options));

// error handler
// no stacktraces leaked to user unless in development environment
app.use(function (err, req, res, next) {
  "use strict";
  utils.sendError(err.status || err.code || 500, err, req, res);
});

Hope it helps!