JavaScript 错误处理:我可以在三元运算符中抛出错误吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9370606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript error handling: can I throw an error inside a ternary operator?
提问by Hristo
Am I allowed to throw an error inside a ternary operator? Is this valid:
我可以在三元运算符中抛出错误吗?这是否有效:
function foo(params) {
var msg = (params.msg) ? params.msg : (throw "error");
// do stuff if everything inside `params` is defined
}
What I'm trying to do is make sure all of the parameters needed, which are in a param
object, are defined and throw an error if any one is not defined.
我想要做的是确保所有需要的参数(位于param
对象中)都已定义,如果未定义任何参数,则抛出错误。
If this is just foolish, is there a better approach to doing this?
如果这只是愚蠢的,是否有更好的方法来做到这一点?
回答by Dagg Nabbit
You could do this:
你可以这样做:
function foo(params) {
var msg = (params.msg) ? params.msg : (function(){throw "error"}());
// do stuff if everything inside `params` is defined
}
I wouldn't really recommend it though, it makes for unreadable code.
不过我真的不推荐它,它会导致代码不可读。
This would also work (not that it's really much better):
这也可以(并不是说它真的好多了):
function foo(params) {
var msg = params.msg || (function(){throw "error"}());
// do stuff if everything inside `params` is defined
}
Or for a cleaner approach, make a named function.
或者为了更简洁的方法,创建一个命名函数。
function _throw(m) { throw m; }
function foo(params) {
var msg = params.msg || _throw("error");
// do stuff if everything inside `params` is defined
}
回答by Ry-
No, it's absolutely not allowed. throw
is a statement and it can't be part of an expression.
不,这是绝对不允许的。throw
是一个语句,它不能是表达式的一部分。
Unfortunately, I think that's the only way. You can use if
s without the braces:
不幸的是,我认为这是唯一的方法。您可以if
在没有大括号的情况下使用s:
if(!params.msg) throw new Error("msg is required!");
But there aren't any nice, easy workarounds that I know.
但是我知道没有任何好的,简单的解决方法。
回答by James Wakefield
Here's a simple little trick that will throw from a ternary. I am simply calling a non-existent, impossible to ever exist, property on the undefined symbol. I have only checked chrome, and it can be caught and re-thrown as shown if you need it to have an appropriate error message but that is unnecessary bloat
这是一个简单的小技巧,可以从三元中抛出。我只是在未定义的符号上调用一个不存在的、不可能永远存在的属性。我只检查了 chrome,如果你需要它有一个适当的错误消息,它可以被捕获并重新抛出,但这是不必要的膨胀
try {
var msg = (params.msg) ? params.msg : (void 0).throwError()
}
catch(e) {
throw new Error('Params has no msg property')
}
回答by Saurabh
You can throw an error like this inside a ternary operator,
您可以在三元运算符中抛出这样的错误,
function isPositive(a) {
if(a > 0)
return "YES";
throw a == 0 ? Error("Zero Error") : Error("Negative Error");
}
回答by bildungsroman
This is a cleaner way that worked for me:
这是一种对我有用的更干净的方法:
const msg = params.msg ? params.msg : ((function () { throw new Error('Message not found); }()));
回答by Sgnl
To build upon @dagg's approach and the named function
example; Here is the same but with default parameters with ES6:
以@dagg 的方法和named function
示例为基础;这是相同的,但使用 ES6 的默认参数:
function _throw(m) { throw new Error(m); }
function foo({ msg = _throw('msg parameter not defined') } = {}) {
console.log(msg);
}
foo({ msg : 'party people!' }); // :D
foo({}); // throws!
回答by Benny Powers
Came across this while using fetch
, here's the solution I offer for that particular case:
在使用时遇到了这个问题fetch
,这是我为这种特殊情况提供的解决方案:
return fetch(url, request)
.then(response => response.status >= 400 && response.status < 600
? response.json().then(error => {throw new Error(error.message)})
: response);
Note the (inline) block around throw
which transforms the arrow-function body from a (return) expression to a statement.
请注意将throw
箭头函数体从(返回)表达式转换为语句的(内联)块。
回答by Yahya Rehman
building on @daggs answer a cleaner approach might be
建立在@daggs 的回答上,一个更简洁的方法可能是
function foo(params) {
var err = function () {
throw "error";
};
var msg = (params.msg) ? params.msg : err();
// do stuff if everything inside `params` is defined
}
回答by Juan Francisco Lobos Galilea
It is not possible and you shouldn't use an anonymous function for that. You'll break the error stack trace for nothing.
这是不可能的,您不应该为此使用匿名函数。您将无缘无故地破坏错误堆栈跟踪。