PJEM
PJEM

Reputation: 677

NodeJS use errors for specific cases

Im using the following function that works ok, However I have some issue with the error handling

e.g.

I want to catch generic error for all the functions

If fn1 or fn2 returns any error the function should throw 'generic error occurred`

Here is the what I need

if getData2 doesn’t have specific property value (see the if) return a uniq error uniq error occurred and not the general error...

This is working example

https://jsfiddle.net/8duz7n23/

async function func1() {
  try {
    const data = await getData1()
    console.log(data)
    const data2 = await getData2();
    if (!data2.url === !"https://test2.com") {
      throw new Error("uniq error occurred  ")
    }
    return data2.url
  } catch (e) {
    throw new Error("generic error occurred ")
  }
}

async function getData1() {
  return "something"
}

async function getData2() {
  return {
    url: "http://test.com"
  }
}

func1().then(result => {
  console.log(result);
}).catch(error => {
  console.log(error);
});

Now If I throw the uniq error the catch will throw the general error.

I want that in case func2 will have some error it still throw away a general error but just if doenst have the right url, trow all the way up the uniq error ...

Is there any cleaner way to do it in nodejs?

I dont want to use an if statement for messages in the catch etc...

I want that the will thrown to the upper level function and not to the catch

Upvotes: 1

Views: 55

Answers (1)

glinda93
glinda93

Reputation: 8489

In order to propagate error to the "upper level", you should have to throw it again in catch block.

You can add your custom error type and check if the error is what you're looking for or not.

class UrlMismatchError extends Error {
  name="UrlMismatchError"
}

async function func1() {
  try {
    const data = await getData1()
    console.log(data)
    const data2 = await getData2();
    if (data2.url !== "https://test2.com") {
      throw new UrlMismatchError("uniq error occured");
    }
    return data2.url
  } catch (e) {
    if (e instanceof UrlMismatchError) {
      throw e;
    } else {
      // handle generic errors
      throw new Error("generic error occured");
    }
  }
}

async function getData1() {
  return "something"
}

async function getData2() {
  return {
    url: "http://test.com"
  }
}

func1().then(result => {
  console.log(result);
}).catch(error => {
  console.error(error.message);
});

I dont want to use an if statement for messages in the catch etc...

I want that the will thrown to the upper level function and not to the catch

No you cannot do that, because javascript is not java, so you cannot do such thing as the follows:

// the code snippet below wont work
try {
  doSomething();
} catch(UrlMismatchError e) {
  // propagate error to the upper level
  throw e;
} catch(Error e) {
  // handle all the other errors
  console.log(e);
}

Upvotes: 1

Related Questions