Mongoose为强制转换错误发出堆栈跟踪 . 我知道如何防止Mongoose错误 - 请不要回答如何防止错误 .
如何在 生产环境 中阻止Mongoose发出堆栈跟踪错误?
错误:传入的参数必须是12个字节的单个字符串或新的ObjectID的24个十六进制字符的字符串(c:\ proj \ fboapp \ node_modules \ mongoose \ node_modules \ bson \ lib \ bson \ objectid.js:38: 11)在C:\ proj \ fboapp \ routes \ user \ no_auth_user_api_routes.js:135:27在Layer.handle [as handle_request](c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ layer.js:95 :5)在Route.dispatch的下一个(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ route.js:131:13)(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ route .js:112:3)在C:\ proj \ fboapp \ node_modules \ express的Layer.handle [as handle_request](c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ layer.js:95:5) \ lib \ router \ index.js:277:22 at Function.process_params(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ index.js:330:12)at next(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ index.js:271:10)在路由器上的Function.handle(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ index.js:176:3)处(c:\ PROJ \ fboapp \ node_modules \表达\ lib中\路由器\ index.js:46:12 )在trim_prefix(c:\ proj \ fboapp \ node_modules \ express \ lib \ router)的Layer.handle [as handle_request](c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ layer.js:95:5) \ index.js:312:13)在c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ index.js:280:7在Function.process_params(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ index.js:330:12)at next(c:\ proj \ fboapp \ node_modules \ express \ lib \ router \ index.js:271:10)
Nodejs v0.12.3 Mongoose v4.4.3
2 回答
一般来说,在代码中添加
try-catch
块可能是正确的方法 .以下是代码中没有
try-catch
块的测试代码,然后防止堆栈跟踪 . 请参阅此模块mongoose disable stack trace
,同时将some new errors添加到mongoose中,并将Error.stackTraceLimit设置为0
将禁用堆栈跟踪收集 .index.js
app.js
输出:
我很困惑为什么在没有错误处理程序的情况下将错误呈现给浏览器,直到我读到ExpressJS error handling documentation page .
显然有 a default error handler 在没有指定错误处理程序时触发 .
最佳做法是为 生产环境 指定自定义错误处理程序,该处理程序不会将堆栈跟踪输出到浏览器 . 默认错误处理程序始终将堆栈跟踪输出到浏览器 .
try-catch块不需要将未捕获的错误路由到自定义错误处理程序,因为Express会自动将未捕获的错误路由到错误处理程序 . 另请注意:错误处理程序中间件必须指定所有4个参数:
err, req, res and next
自定义错误处理程序的示例: