JS库最佳实践:返回未定义或抛出错误的错误的函数输入? [英] JS library best practice: Return undefined or throw error on bad function input?
本文介绍了JS库最佳实践:返回未定义或抛出错误的错误的函数输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript中编写库时,处理函数的无效输入的最标准(最友好的)方法是什么?我的肠道告诉我,返回未定义是完全正常,但是它实际上更有帮助,抛出一个错误?或者它真的没关系吗?
我也可以看到返回false,null甚至-1,但我不认为这些将被广泛预期。 p>
(如果这个问题太主观,我很高兴把它变成cw。)
解决方案
异常的优点:
- 如果错误是罕见的(正常运行时不会发生)对于调用代码在一个更高级别的地方捕获异常而不是在每次API调用后测试返回值都更容易和更快。
异常的缺点:
- 捕获异常比测试返回值慢很多,因此如果错误是常见的情况,
- 如果调用代码要检查每个API调用中的错误(而不是在更高级别捕获异常),则异常更难以写入围绕每个API调用,而不仅仅是测试返回值。
When coding a library in JavaScript, what is the most standard (friendliest?) way to handle invalid input to a function? My gut tells me that returning undefined is perfectly fine, but is it actually more helpful to throw an error instead? Or does it really not matter?
I could also see returning false, null or even -1, but I don't think those would be as widely expected.
(If this question is too subjective, I'm happy to make it cw.)
解决方案
Advantages of exceptions:
- If an error is a rare occurrence (not expected in normal operation), then it may be easier and faster for the calling code to catch exceptions in one higher-level place rather than test return values after every API call.
Disadvantages of exceptions:
- Catching an exception is a lot slower than testing a return value so if an error is a common occurrence, then exceptions will be a lot slower.
- If the calling code is going to check errors on every API call they make (and not catch exceptions at a higher level), exceptions are more of a pain to write around every single API call than just testing a return value.
这篇关于JS库最佳实践:返回未定义或抛出错误的错误的函数输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文