matjaz/node-http.min

Unexpected token < in JSON at position 0

oh2th opened this issue · 2 comments

oh2th commented

Every now and then an API returns garbage instead of the expected JSON.

Could the parseJSON first verify that it actually is parseable instead of getting a SyntaxError from JSON.parse()?

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at parseJSON (/app/node_modules/http.min/index.js:106:24)
at IncomingMessage. (/app/node_modules/http.min/index.js:60:22)
at IncomingMessage.emit (node:events:529:35)
at IncomingMessage.emit (node:domain:489:12)

matjaz commented

Can you provide an example?

Invalid JSON is covered by this test.

node-http.min/test/index.js

Lines 264 to 273 in bb29b81

describe('errors', function () {
it('should be handled', function () {
nock('http://example.com')
.get('/test')
.replyWithError('nooooo')
return http.json('http://example.com/test').catch(function (err) {
expect(err.name).to.equal('Error')
expect(err.message).to.equal('nooooo')
})
})

I am not fond of checking response content. We could check content-type header.

oh2th commented

Found what the issue is, the upstream API returns HTML page while there was Backend server error. Adding now check for result.response.statusCode. So it should be fine. Just so surprised that the API fails so often, and that is not in my hands.

This case can be closed.