Reputation: 14526
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!
Upvotes: 3
Views: 2233
Reputation: 2780
Hi @dublx I think there are perfectly valid use cases to use assertions in the production code. E.g. if you rely on an external API that you know to behave in a certain way. This API might change suddenly and break your code. If an assertion would detect that the API changed and you would get an automatic e-mail you then could fix it even before your customers will recognize the break.
That said I recommend assume.js which solves exactly your problem. Even the performance is splendid: One assertion eats just 17µs or 0.017ms.
Upvotes: 0
Reputation: 5241
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.
Upvotes: 0