Node.js: should `assert ()` s be stored in production code?

Methodological issue:

I am implementing an API for some services using node.js, mongodb and express.js.

On many (almost all) sites, I see this code:

method(function(err, data) { assert.equal(null, err); }); 

The question is: should assert instructions be stored in my code during production (at least for low-value errors)? Or, is this just for testing the code, and should I better handle all errors every time?

+5
source share
2 answers

probably no

ref: When should statements be kept in production code?

Basically in my code I put the error handling function in a separate file and everywhere I use the same error method, basically it depends on the logic

how ppl generally forget about it

 process.on('uncaughtException', function (err) { console.log(err); }) 

and err == null does not hurt, it checks both null and undefined

+1
source

You must not ultimately keep them in a working environment.

If you advertise a little Google, there are many alternative approaches to eliminate them.

Personally, I use the null object template, implementing two wrappers in a separate file: the first maps its method directly to the one that was exported by the assert module, the latter offers empty functions and nothing more.

Thus, at runtime, you can connect the correct one by relying on some global variable pre-set correctly, for example process.env.mode . In your files you only need to import the above module and use it instead of using assert directly.

Thus, throughout your code, you will never see how error-prone material such as myAssert && myAssert(cond) , instead you will have the ever cleaner and safer myAssert(cond) statement.

The following is a brief example:

 // myassert.js var assert = require('assert'); if('production' === process.env.mode) { var nil = function() { }; module.exports = { equal = nil; notEqual = nil; // all the other functions }; } else { // a wrapper like that one helps in not polluting the exported object module.exports = { equal = function(actual, expected, message) { assert.equal(actual, expected, message); }, notEqual = function(actual, expected, message) { assert.notEqual(actual, expected, message); }, // all the other functions } } // another_file.js var assert = require('path_to_myassert/myassert'); // ... your code assert(true, false); // ... go on 
+4
source

Source: https://habr.com/ru/post/1233529/


All Articles