Home > Enterprise >  Unable to catch error when fetching data in async function
Unable to catch error when fetching data in async function

Time:08-28

I'm using npm yahoo-finance to fetch stock data. When I input a stock symbol that doesn't exist, I would like to catch the error.

const yahooFinance = require('yahoo-finance');

async function stockData() {

try {
        let data = await yahooFinance.historical({symbol: "SIJGAOWSFA", from: 2020-08-23, to: 2021-08-23});
    } catch (error) {
        console.error(error)
    }
}

stockData();

However it doesn't appear to be a typical fetch error. It's not being caught at all. By that I mean, the error you see below was not logged to the console via the console.error(error). Rather something outside the scope of this file is logging the error. When the error occurs, nothing in catch is executed.

enter image description here

I plan on using this in a for loop, so would like to catch the error so I can avoid executing any following functions.

CodePudding user response:

A collaborator says that:

Is this from an existing project that was working and stopped working, or a new project?

If the former - everything is still working fine on my side. (Very) occasionally there are issues at yahoo that get stuck in their cache, possibly relating to DNS too. I'd suggest to clear your DNS cache and also try querying different data to see if that works.

If the latter (new project), it could be the data you're querying. Try query different data and see if it works. Usually yahoo throws back a specific error if something wrong, but it could be this.

If neither of those approaches work, but you still need to catch this sort of error, given the source code, what it does is:

if (!crumb) {
  console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb '  
    'structure no longer exists, please open an issue.');

And then continues on as normal (without throwing), and eventually returns an empty array.

If you're sure the result should contain at least one item, you can check to see if it's empty, and enter into an error state if it is.

Otherwise, if you don't know whether the array should contain values or not, another option is to overwrite console.warn so that you can detect when that exact string is passed to it.

Another option would be to fork the library so that it (properly) throws an error when not found, instead of continuing on and returning an empty array, making an empty successful result indistinguishable from an errored empty result. Change the

if (!crumb) {
  console.warn('root.Api.main context.dispatcher.stores.CrumbStore.crumb '  
    'structure no longer exists, please open an issue.');

to

if (!crumb) {
  throw new Error('root.Api.main context.dispatcher.stores.CrumbStore.crumb '  
    'structure no longer exists, please open an issue.');

and then you'll be able to catch it in your call to .historical.

  • Related