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.

3
  • 3
    if(!resultSpec) throw new Error() ? throw is a statement, not an expression. Commented May 14, 2020 at 14:29
  • Does this answer your question? How to check a not-defined variable in JavaScript Commented May 14, 2020 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. Commented May 14, 2020 at 14:44

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

There's no point wrapping this in a try...catch just to rethrow the error.
@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
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")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.