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?
- When I try to access an URL that doesn't exists inside
routes.tsit 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.