First thing first:
It's really up to you to decide wether you should or shouldn't throw
exception rather than return
an error code (or null
, or whatever).
As far as I know there're no great issues in throwing exceptions rather than returning errors as far as you handle them properly.
This leads to the following question:
When is correct to throw an exception (or Error in JS)?
The question is pretty tricky, and here should be flagged and closed as "primarily opinion based" since this is up to personal opinion.. well, maybe..
A similar question (well.. this exact question) has already been asked and replied here and I find myself agreeing with the accepted answer, summed up in this comment:
Exactly! An exception is thrown when and only when function preconditions (assumptions about arguments) are broken! – @Lightman
In your situation, if the assumptions of your function (your expected parameter) are violated: YES, throw an exception, since JS doesn't provide any syntax construct to set a function parameter as required
.
With ES6 you can use
default parameters
to force something like the behaviour you want:
function required() {
throw new Error('Missing parameter');
}
function foo(aRequiredParameter = required()) {
// Use your required parameter
console.log("Hello " + aRequiredParameter);
}
// Hence:
foo("World") // OK
foo() // -> Throws exception
Example taken from here, while here you can find more examples about this feature.
This is achievable because, when aRequiredParameter
is not passed it's default value will be assigned (in this case invoked) and hence the exception/error will be threw.