Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript error handling: can I throw an error inside a ternary operator?

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?

like image 348
Hristo Avatar asked Feb 21 '12 00:02

Hristo


People also ask

Does throwing a new error stop execution?

throw new Error('something went wrong') — will create an instance of an Error in JavaScript and stop the execution of your script, unless you do something with the Error.

Does throwing an error stop execution JavaScript?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

Can you do else if in ternary operator JavaScript?

However, JavaScript allows you to construct nested ternary operators to replace if…else…else if statements. To an expression like this using the nested ternary operator: console.

How do you throw an error message in JavaScript?

create(Error. prototype); With a custom exception object created, all we have to do is throw it like any other error: throw new CustomException('Exception message');


1 Answers

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 } 
like image 108
Dagg Nabbit Avatar answered Sep 25 '22 22:09

Dagg Nabbit