Search code examples
node.jsexceptionasserthandleshould.js

How to handle should.js assert error


How should one handle uncaught exception thrown by a should.js (or node.js) failed assertion and keep execution on the same function/block where the assertion failed?

I tried wrapping the assertion in a try/catch but it seems to go up to process.on('uncaughtexception') anyway.

Lastly, is it a good practice and performant to use assertions in your production code to validate object properties?

Thanks!


Solution

  • As the documentation states, Node's assert is basically for unit testing. Therefore I wouldn't use it in production code. I prefer unit testing to make sure that assertions are true in several situations.

    However, I think you are using assert in a wrong way here: If an assertion fails something is wrong. Your app is in some kind of unknown state.

    If you have some kind of handling for invalid objects assert isn't the right tool: As far as I understand your usecase you don't really require an object to be valid, but want to do something different if it's not. That's a simple condition, not an assertion.