0

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.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Sheen
  • 586
  • 10
  • 22
  • 3
    `if(!resultSpec) throw new Error()` ? `throw` is a statement, not an expression. – Jonas Wilms May 14 '20 at 14:29
  • Does this answer your question? [How to check a not-defined variable in JavaScript](https://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript) – Heretic Monkey May 14 '20 at 14:33
  • You could do `return resultSpec || new Error();` if you actually want to return an error like your title says, but your question body says you want to throw the error and stop executing, so you just need to determine if the variable is undefined (which can be answered by the linked question's answers) and throw an error. – Heretic Monkey May 14 '20 at 14:44

2 Answers2

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

awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • 1
    There's no point wrapping this in a `try...catch` just to rethrow the error. – Patrick Roberts May 14 '20 at 14:32
  • 1
    @PatrickRoberts well of course, but I don't know if OP ever plans on adding any different error handling for errors that could be thrown by the promise or `undefined` property accesses so I just left that part of it untouched – awarrier99 May 14 '20 at 14:36
1

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")
Penny Liu
  • 15,447
  • 5
  • 79
  • 98