0

I seem to be unable to catch exceptions from response.json()

    page.on('response', async res => {
      if (res.request().resourceType() == 'xhr') {
        if (res.url() == search_prefix) {
          console.log(res.status(),res.url())
          try {
            const data = await res.json()
            if (data != undefined && data.status == "success") {
                results = parseResults(data,config)
            }
          }
          catch (error) {}
        }
      }
    })

I only have one place in my code where I am parsing json from a response. I have a webpage that sometimes gives invalid JSON data. I am expecting the above code to catch the json exception and continue executing. However, the exception is caught in my "uncaught" exception handling.

eng3
  • 431
  • 3
  • 18
  • This looks fine to me. Can you provide a [mcve]? – ggorlen Oct 29 '22 at 18:05
  • This occurs randomly depending on the whim of the website. Is there a way to force the response to be undefined? – eng3 Oct 29 '22 at 23:48
  • Which site and what response? I can't really help without something to run and observe the problem on. `results = parseResults(data,config)` looks [pretty questionable](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) as well. – ggorlen Oct 29 '22 at 23:58
  • Any site, I've had it happen on cnn.com but it doesnt happen every time, the bad JSON is completely random. I just want to handle/ignore it. That is why I ask if there's a way to hardcode in a bad JSON response to see if I can create something reproducible. parseResults is just my function to read the JSON. It is irrelevant, I've tried removing it and the error still occurs sometimes. The "uncaught" exception is on the res.json() line – eng3 Oct 30 '22 at 01:25
  • Sure, you can mock `fetch` and plug in any response to make it reproducible. What's the point of this code anyway? There may be a [better way to do whatever you're trying to do](https://meta.stackexchange.com/a/233676/399876) if you provide more context. I still see no way you can have an uncaught exception when it's pretty clearly being caught, hence the request for the runnable [mcve]. There are too many missing gaps here, like `search_prefix`. – ggorlen Oct 30 '22 at 01:38
  • Minor code nitpick, not the problem here: always use `===` rather than `==` which does surprising things and will lead you to bugs inevitably. Any good linter will complain. You can also use `&&` to combine booleans and reduce nesting. – ggorlen Oct 30 '22 at 01:45
  • ok, I'll give that a try and try to make something that is reproducible. I'm just trying to look for a json response and save certain pieces of data from it. I think it is pretty clear that it should be catching the exception too, but it reports an uncaught exception. That is why I made this post. Yes, I should use something with a linter vs notepad – eng3 Oct 30 '22 at 01:56

0 Answers0