Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

If this is just foolish, is there a better approach to doing this?

question from:https://stackoverflow.com/questions/9370606/javascript-error-handling-can-i-throw-an-error-inside-a-ternary-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
637 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...