Skip to content

Commit

Permalink
Handle JSON.parse failure (#10)
Browse files Browse the repository at this point in the history
* Handle JSON.parse failure

* Pass on original error instead of JSON parse exception

* Add tests
  • Loading branch information
spencerfdavis committed Feb 12, 2019
1 parent 25f6161 commit 0fe7417
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/gimme.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { Readable } = require('stream')

const {
assoc, assocPath, evolve, flip, identity, is,
length, merge, pick, pipe, replace, when
merge, nthArg, pick, pipe, replace, tryCatch
} = require('ramda')

const parseBody = require('./parseBody')
Expand All @@ -20,7 +20,7 @@ const clean = pipe(
evolve({ headers: redact })
)

const parseJSON = when(length, JSON.parse)
const parseJSON = tryCatch(JSON.parse, nthArg(1))

const gimme = opts => {
const { json = true } = opts
Expand Down
1 change: 1 addition & 0 deletions test/00-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ beforeEach(() => {
nock(url).post('/').query(true).reply(respond('POST'))
nock(url).get('/error').query(true).reply(400)
nock(url).get('/no-length').query(true).reply(200, { foo: 'bar' })
nock(url).get('/non-json-error').query(true).reply(400, 'string error')
})

afterEach(() =>
Expand Down
13 changes: 13 additions & 0 deletions test/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ describe('errors', () => {
res(undefined)
})

describe('non JSON formatted error', () => {
beforeEach(() =>
gimme({ url: `${url}/non-json-error` }).catch(res)
)

it('rejects with an appropriate Boom error', () => {
expect(res()).to.be.a('Error')
expect(res().isBoom).to.be.true
expect(res().output.statusCode).to.equal(400)
expect(res().data.res.body).to.equal('string error')
})
})

describe('when statusCode >= 400', () => {
beforeEach(() =>
gimme({ url: `${url}/error` }).catch(res)
Expand Down

0 comments on commit 0fe7417

Please sign in to comment.