3

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!

dublx
  • 11,978
  • 1
  • 14
  • 11

2 Answers2

0

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.

Sebastian vom Meer
  • 5,005
  • 2
  • 28
  • 36
  • Thanks, it makes sense. My reason to use should.js to validate an object is that it is fairly descriptive and i could re-use code from my unit tests. – dublx Apr 12 '13 at 11:23
0

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.

analog-nico
  • 2,750
  • 17
  • 25