β

Answer by zangw for Prevent Mongoose stack trace f

User zangw - Stack Overflow 187 阅读

Generally speaking, add try-catch block in the codes could be correct way to do it.

Here are my test codes without try-catch block in codes, then prevent stack trace. Refer to this module mongoose disable stack trace , also add some new errors are added into mongoose, and set Error.stackTraceLimit to 0 will disable stack trace collection.


index.js

const captureStackTrace = Error.captureStackTrace;
const CastError = module.parent.require('mongoose/lib/error/cast');
const VersionError = module.parent.require('mongoose/lib/error/version');
const ValidatorError = module.parent.require('mongoose/lib/error/validator');
const ValidationError = module.parent.require('mongoose/lib/error/validation');
const OverwriteModelError = module.parent.require('mongoose/lib/error/overwriteModel');
const MissingSchemaError = module.parent.require('mongoose/lib/error/missingSchema');
const DivergentArrayError = module.parent.require('mongoose/lib/error/divergentArray');
Error.captureStackTrace = function( that, params) {
    if(that instanceof CastError ||
        that instanceof VersionError ||
        that instanceof ValidatorError ||
        that instanceof ValidationError ||
        that instanceof OverwriteModelError ||
        that instanceof MissingSchemaError ||
        that instanceof DivergentArrayError) {
        Error.stackTraceLimit = 0;
    } else if (typeof that !== 'undefined'){
        captureStackTrace.apply(Error, arguments);
    }     
}
Error.captureStackTrace(new VersionError);

app.js

require('mongoose-disable-stack-trace');
var f = Foo({_id: new ObjectId('adss112'), key: '123'}); // invalid ObjectId

Output:

Error: Argument passed in must be a single String of 12 bytes or a string of 24
hex characters
c:\share\node\node_modules\mongoose\node_modules\mongodb\lib\server.js:283
      process.nextTick(function() { throw err; })                                  ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24
hex characters
作者:User zangw - Stack Overflow
most recent 30 from stackoverflow.com
原文地址:Answer by zangw for Prevent Mongoose stack trace f, 感谢原作者分享。

发表评论