#trying to figure out how to use try properly

7 messages · Page 1 of 1 (latest)

fickle flax

im a bit confused on how to use try, new to javascript so sorry if i explain this poorly,

  if (interaction.commandName === "quote") {
    fetch("https://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en").then(
        async (res) => {
        let quote = await res.json();

        console.log(quote);

      }
    );
  }```
im making a command that calls an API to give a random quote, it works 99% of the time but when it gives an error like:

```javascript
node_modules\node-fetch\lib\index.js:273
                                return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
                                                           ^
FetchError: invalid json response body at https://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en reason: Bad escaped character in JSON at position 39
    at C:\Users\Bubba\Desktop\SakioliBot\node_modules\node-fetch\lib\index.js:273:32
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async C:\Users\Bubba\Desktop\SakioliBot\index.js:328:21 {
  type: 'invalid-json'
}```

would i use try to figure this out (ive tried i cant seem to get it)

can anyone help?
errant magnetBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by OP
fickle flax

also let me iterate that i know its invalid json i just dont know what to do to catch exactly what "json" is causing this crash

rain shadow

Sometimes the API gives a quote with escape of the apostrophe (\') which is invalid.
Just wrap the try over the fetch.

try {
  await fetch('...');
} catch (error) {
  // handle error
}

Or use <Promise>.catch()

await fetch('...').catch((error) => { //** handle error **// });
lethal bayBOT

mdn try...catch
The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.

mdn Promise.prototype.catch()
The catch() method of Promise instances schedules a function to be called when the promise is rejected. It immediately returns an equivalent Promise object, allowing you to chain calls to other promise methods. It is a shortcut for Promise.prototype.then(undefined, onRejected).

fickle flax

gonna try this, thank you