'How do I return an error if value is undefined in Node/JavaScript?
I am running a query to return some data
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items[0].spec;
return resultSpec;
} catch (e) {
throw new Error(e);
}
}
How do I check if resultSpec is undefined and if so throw and error and stop executing?
I have tried
return resultSpec || throw new Error() however get syntax errors when I try that.
Solution 1:[1]
Just use an if statement:
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items[0].spec;
if (!resultSpec) throw new TypeError('Spec is undefined');
return resultSpec;
} catch (e) {
throw new Error(e);
}
}
As mentioned by others, if you don't plan on doing any error handling in your catch block other than to simply rethrow the error, the try/catch is not necessary here, as you can just let whichever function that calls getIngress handle it
Solution 2:[2]
You don't need the try and catch statement if you're not handling errors in that function.
if (resultSpec == undefined) throw Error("The result is undefined")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Penny Liu |
