Skip to content

Commit

Permalink
fix: handling some unhandled error cases (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
rchl authored and manniL committed Aug 15, 2019
1 parent 6536afc commit 6ab0a2b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
18 changes: 16 additions & 2 deletions lib/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,25 @@ module.exports = function (options) {
// 2) string
// 3) function taking from & req (when from is regex, req might be more interesting)

const toTarget = typeof foundRule.to === 'function' ? await foundRule.to(foundRule.from, req) : foundRule.to
let toTarget

try {
toTarget = typeof foundRule.to === 'function' ? await foundRule.to(foundRule.from, req) : foundRule.to
} catch (error) {
return next(error)
}

const toUrl = decodedBaseUrl.replace(foundRule.from, toTarget)

try {
res.setHeader('Location', toUrl)
} catch (error) {
// Not passing the error as it's caused by URL that was user-provided so we
// can't do anything about the error.
return next()
}

res.statusCode = foundRule.statusCode || options.statusCode
res.setHeader('Location', toUrl)
res.end()
}
}
4 changes: 4 additions & 0 deletions test/fixture/redirects.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,9 @@ module.exports = [
const param = req.url.match(/functionAsync\/(.*)$/)[1]
setTimeout(() => resolve(`/posts/${param}`), 2000)
})
},
{
from: '^/errorInToFunction$',
to: () => Promise.reject(new Error('forced error'))
}
]
18 changes: 18 additions & 0 deletions test/module.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,24 @@ const testSuite = () => {
expect(html).toContain('Works!')
})

test('redirect error with control character', async () => {
const requestOptions = {
uri: url(encodeURI('/mapped/ab\u0001')),
resolveWithFullResponse: true
}

await expect(request(requestOptions)).rejects.toHaveProperty('statusCode', 404)
})

test('redirect error with failing "to" function', async () => {
const requestOptions = {
uri: url('/errorInToFunction'),
resolveWithFullResponse: true
}

await expect(request(requestOptions)).rejects.toHaveProperty('statusCode', 500)
})

test('many redirect', async () => {
for (const n of ['abcde', 'abcdeasd', 'raeasdsads']) {
const html = await get(`/many/${n}`)
Expand Down

0 comments on commit 6ab0a2b

Please sign in to comment.