Talita
Talita

Reputation: 835

How to set or change swagger 404 response type

I generated an app using swagger-node (https://github.com/swagger-api/swagger-node). I am using the swagger validator to find validation errors. It works fine, I am catching errors and changing them to the response format I prefer.

I would like to handle also 404 error and return my own response. Swagger returns automatic response when URL of a nonexisting page is provided and I would like to change it to my response.

Swagger response:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /fhello</pre>
</body>
</html>

I am looking for the way of changing it (to JSON).

Upvotes: 1

Views: 3751

Answers (1)

Talita
Talita

Reputation: 835

Ok, I solved it.

The response I am getting is not from the swagger-node-runner or similar but from finalhandler module used by express.

So I was not handling 404 error in my server.

To handle 404 in the project generated by swagger-node one just have to add a middleware at the end of the path of middlewares, managing all the queries which were not caught by the previous middlewares.

  app.use(function(req, res, next) {
      return res.status(404).json({description: 'Page not found'});
  })

(and what was probably my main mistake - I was using a middleware with four parameters app.use(function(err, req, res, next) {}

Upvotes: 2

Related Questions