抛出字符串而不是错误 [英] Throwing strings instead of Errors

查看:118
本文介绍了抛出字符串而不是错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我们可以在Javascript中使用 throw 关键字抛出任何内容,我们不能直接抛出错误消息字符串吗?

Since we can throw anything with the throw keyword in Javascript, can't we just throw an error message string directly?

有没有人知道这个中的任何问题?

Does anyone know any catch in this?

让我为此添加一些背景:很多时候,在JavaScript世界中,人们依赖于参数检查反对使用try-catch机制,因此只使用 throw 抛出致命错误是有意义的。仍然,为了能够捕获一些系统错误,我必须为我自己的错误使用不同的类,而不是创建Error的子类,我想我应该只使用String。

Let me add some background to this: Very often, in the JavaScript world, people rely on parameter checking as opposed to using the try-catch mechanism, so it makes sense to only throw fatal errors with throw. Still, to be able to catch some system Errors, I have to use a different class for my own errors and instead of creating a subclass of Error, I think I should just use String.

推荐答案

可以抛出任何你喜欢的东西,但请记住,如果catch不在你自己的代码之外,它可能会期望一个完整的Error实例而不是一个普通的字符串。

It is okay to throw whatever you like, but keep in mind that if the catch is outside of your own code, it might expect a full Error instance and not a plain string.

这篇关于抛出字符串而不是错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆