0

I'm building a small microservice with express, and I'd like to know how to avoid undefined routes, i.e:

In my API, I'v defined just and endpoint,

/api/myendpoint

Which works as expected, but if I send any kind of reques to the same host+server where express is running, i.e

/api/route/dont/exist

I get a ugly html response, which I would like to avoid, or return some kind of custom message

I been digging a bit but I coulnt find any solution

Thanks in advance!

SeekanDestroy
  • 511
  • 1
  • 5
  • 12
  • 1
    https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs – Phix Feb 12 '21 at 01:06

1 Answers1

2

Custom error handling in Express.

In a nutshell, it looks like this:

// custom error handler
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
});

You put this after your other middleware. See the documentation link above for more info. This lets you control what response is sent back to the client if a route handler is not found for the specific incoming request or if any route calls next(err) with an error. This middleware handler will only get called in those cases of an error. You can then send any response you want.

jfriend00
  • 683,504
  • 96
  • 985
  • 979