response.json() can throw an error in JavaScript

Published on in JavaScript

If the response body is not valid JSON, response.json() will throw, just like JSON.parse() would throw if the same data was passed to it.

Example:

const response = new Response('{ "foo": true }')
await response.json()
//=> { foo: true }

// vs

const response = new Response('OK')
await response.json()
//=> SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Quite obvious in hindsight, but I was wondering this and couldn't find an answer quickly (I tried googling "can response.json throw in js").

How about response.text() – can it throw? No, because it's akin to passing the same data to the String() function, which doesn't seem to throw according to the language specs. (Compare with the language specs of JSON.parse(); throwing is mentioned in step 2.)