You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express电商应用报错TypeError: errorHandler is not a function求助

错误排查:TypeError: errorHandler is not a function 解决方法

问题根源

报错核心原因有两个:

  • 自定义的error-handler.js模块未导出函数,导致require后无法获取可用的函数引用
  • app.js中错误调用errorHandler(),而非直接传递函数本身给app.use

分步解决

1. 修复自定义错误处理模块的导出

打开error-handler.js,在代码末尾添加模块导出语句,让外部可以引用该函数:

function errorHandler(err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        return res.status(401).json({message: 'The user is not authorized'})
    }

    if (err.name === 'ValidationError') {
        return res.status(400).json({message: err.message}) // 验证错误属于客户端请求问题,改成400更合理
    }

    return res.status(500).json({message: err.message || 'Internal Server Error'});
}

// 关键:导出错误处理函数
module.exports = errorHandler;

2. 修正app.js中的中间件使用方式

Express错误处理中间件需要传递函数引用,而非调用函数。修改app.js对应行:

// 原错误代码
app.use(errorHandler())

// 修改为
app.use(errorHandler)

3. 清理多余依赖(可选)

你执行的npm install errorhandler安装了第三方错误处理包,但当前代码并未使用该包,而是用自定义的error-handler.js模块。若不需要这个第三方包,可卸载:

npm uninstall errorhandler

内容的提问来源于stack exchange,提问作者pierre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 00:39:24