【发布时间】:2021-07-18 23:15:17
【问题描述】:
服务器.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'))
在其他 app.use() 和路由调用之后,您最后定义错误处理中间件;
所以我认为这是对的。但由于某种原因,它没有被调用/触发。
为什么它不起作用?
- 当我尝试访问
routes.ts中不存在的 URL 时,它会给出标准 404 错误,但我想从我的中间件中获取它。
我想将此中间件用于所有错误,但大多数用于当用户请求不存在的端点时。
【问题讨论】:
标签: javascript node.js express