Reputation: 2923
Server.ts
import express, { Request, Response, NextFunction } from 'express'
import { router } from "./routes"
import { Database } from './Database/index'
const app = express()
const db = new Database()
db.connect()
app.use(router) // contains all my routes
// The middleware I'm trying to be fired
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof Error) {
return res.status(400).json({
error: err.message
})
}
return res.status(500).json({
status: 'error',
message: 'Internal Server Error :('
})
})
app.listen(3000, () => console.log('Server is running'))
According to Express4 Documentation
You define error-handling middleware last, after other app.use() and routes calls;
So I think it's right. But for some reason its NOT being called/triggered.
Why it's NOT working?
routes.ts
it gives a standard 404 error, but I want to get it from my middleware.I want to use this Middleware for all errors, but most for when user makes a request for an endpoint that doesn't exists.
Upvotes: 1
Views: 161
Reputation: 20376
This is because in 404 is not an error. It just means there is no matching route.
From the docs:
In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them.
This is the default code from the docs. Add this at the bottom:
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
Upvotes: 1