Node.js应用如何选择对应的中间件函数?
Express中间件执行逻辑:何时调用errorMiddleware和notFoundMiddleware?
我在应用里通过app.use()加载了errorMiddleware和notFoundMiddleware两个中间件,但不清楚应用是怎么判断何时用哪个的。比如当访问不存在的页面时,notFoundMiddleware会运行,想知道Express是如何在这两个中间件中做选择的?
app.js 文件
require('dotenv').config() // async errors const express = require('express'); const app = express(); const notFoundMiddleware = require('./middleware/not-found') const errorMiddleware = require('./middleware/error-handler') // middleware app.use(express.json()) // routes app.get('/',(req,res)=>{ res.end('<h1>Store API </h1><a href = "/api/v1/products">product route</a>') }) // product route app.use(errorMiddleware) app.use(notFoundMiddleware) const port = process.env.PORT || 3000 const start = async() =>{ try{ app.listen(port,console.log("server is listening")) } catch(e){ } } start();
error-handler.js 文件
const errorHandlerMiddleware = async(err,req,res,next)=>{ console.log(err) return res.status(500).json({msg:'something went wrong, We are sorry for the inconvenience'}) } module.exports = errorHandlerMiddleware
not-found.js 文件
const notFound = (req,res)=>{ return res.status(404).send('Route does not exist') } module.exports = notFound
核心逻辑:Express中间件的执行规则
Express对这两个中间件的调用,核心看类型区分和注册顺序两个关键点:
中间件类型差异
errorMiddleware是错误处理中间件:它的函数签名包含err参数((err, req, res, next)),这是Express识别错误处理中间件的标志。只有当请求流程中出现错误(比如路由里调用next(err)、同步代码抛异常、异步代码未捕获错误)时,Express才会触发这类中间件。notFoundMiddleware是普通中间件:函数签名无err参数,Express会在所有路由都未匹配到请求时,按顺序执行这类兜底的普通中间件。
注册顺序的影响
你当前的代码把错误处理中间件放在了404中间件前面,虽然404场景能正常触发,但存在逻辑隐患——错误处理中间件应该放在所有路由和普通中间件的最后,否则前面路由抛出的错误可能无法被正确捕获。正常的执行流程应该是:
- 请求进来后,Express从上到下匹配已注册的路由,匹配到则执行对应处理函数;
- 若所有路由都未匹配,执行后续的普通中间件(即
notFoundMiddleware),返回404; - 若路由/中间件处理中出现错误,Express会跳过后续普通中间件,直接找到第一个错误处理中间件执行,返回500错误。
修正后的注册顺序
调整顺序才能让两类中间件各司其职:// 先注册所有路由 app.get('/',(req,res)=>{ res.end('<h1>Store API </h1><a href = "/api/v1/products">product route</a>') }) // 然后是404兜底中间件 app.use(notFoundMiddleware) // 最后是错误处理中间件 app.use(errorMiddleware)
内容的提问来源于stack exchange,提问作者Syed Ilhan
相关产品推荐
相关产品推荐

