Sheen
Sheen

Reputation: 708

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.

Upvotes: 0

Views: 2054

Answers (2)

Mohamed Belkheir
Mohamed Belkheir

Reputation: 179

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")

Upvotes: 1

awarrier99
awarrier99

Reputation: 3855

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

Upvotes: 1

Related Questions