我们可以把错误,分成多个模块去处理它
比如 一个中间件是打印错误, 另外一个是错误数量统计, 通过next()来传递。
重点:next(error)
当next传入了参数(string || buffer)之后,会直接进入errorHandler,不执行后面的中间件。
下面的代码是自定义的一个errorHandler,很简单,就是app.use()传三个参数和四个参数的区别。
文档https://www.expressjs.com.cn/guide/error-handling.html
const app = express();app.use((req, res, next) => {res.write('1');next();});app.use((req, res, next) => {res.write('2222');if (true) {next('未登录');}next();});app.use((req, res, next) => {res.write('3');next();});app.use((error, req, res, next)=> {console.log(error)next(error)})let count = 0app.use((error, req, res, next)=> {count +=1console.log(`目前有${count}个错误`)next(error)})app.listen(3000, () => {console.log('正在listen 3000');});
每请求一次(刷新一次localhost:3000) 就会+1
