serpapi / google-search-results-nodejs

SerpApi client library for Node.js. Previously: Google Search Results Node.js.
https://serpapi.com
MIT License
79 stars 22 forks source link

Node Crashes due to Dangling Promise? #20

Open chrisrosner opened 1 year ago

chrisrosner commented 1 year ago

Hey folks, maybe I'm hitting my limits of js/node.js knowledge, but I am having trouble understanding how to catch certain classes of error with this library in an async/promise context.

Specifically, node.js crashes if you pass an empty string query to the json method, eg:

let client = new serpapi.GoogleSearchResults(api_key) client.json({}, (data) => {done();})

It looks like there used to be a unit test for this, but it has been removed.

https://github.com/serpapi/google-search-results-nodejs/commit/10aadf89a96c9940eae666b47ae555a0a425dd23 "xit("fail:json", (done) => {"

Looking at the implementation, https://github.com/serpapi/google-search-results-nodejs/blob/master/lib/SerpApiSearch.js#L89C11-L89C16, it seems that any response from google that is not a 200 response will throw an exception that is impossible to catch, leading to dangling promises and node.js crashing.

Is the library broken? Is there a different pattern I should use to catch these exceptions?

I'm using the suggested pattern from this page: https://serpapi.com/integrations/node#promise-and-callback

const getJson = () => { return new Promise((resolve) => { search.json(params, resolve); }); };

ilyazub commented 5 months ago

Hi @chrisrosner. I'm sorry for the late reply.

You can handle errors in the getJson function:

function getJson(params) {
  return new Promise((resolve, reject) => {
    try {
      search.json(params, resolve)
    } catch (e) {
      reject(e)
    }
  })
}

Related to https://github.com/serpapi/google-search-results-nodejs/issues/4.