Gracefully handle failed network requests

This commit is contained in:
Yarmo Mackenbach 2020-12-10 23:22:46 +01:00
parent d8a14abac3
commit 0efa5350a5

View file

@ -72,15 +72,31 @@ const directRequestHandler = (spData, opts) => {
switch (spData.proof.format) { switch (spData.proof.format) {
case 'json': case 'json':
res = await req(url, null, { req(url, null, {
Accept: 'application/json', Accept: 'application/json',
'User-Agent': `doipjs/${require('../package.json').version}`, 'User-Agent': `doipjs/${require('../package.json').version}`,
}) })
resolve(await res.json()) .then(async (res) => {
return await res.json()
})
.then((res) => {
resolve(res)
})
.catch((e) => {
reject(e)
})
break break
case 'text': case 'text':
res = await req(url) req(url)
resolve(await res.text()) .then(async (res) => {
return await res.text()
})
.then((res) => {
resolve(res)
})
.catch((e) => {
reject(e)
})
break break
default: default:
reject('No specified proof data format') reject('No specified proof data format')
@ -92,13 +108,20 @@ const directRequestHandler = (spData, opts) => {
const proxyRequestHandler = (spData, opts) => { const proxyRequestHandler = (spData, opts) => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const url = spData.proof.fetch ? spData.proof.fetch : spData.proof.uri const url = spData.proof.fetch ? spData.proof.fetch : spData.proof.uri
const res = await req( req(
utils.generateProxyURL(spData.proof.format, url, opts), utils.generateProxyURL(spData.proof.format, url, opts),
null, null,
{ Accept: 'application/json' } { Accept: 'application/json' }
) )
const json = await res.json() .then(async (res) => {
resolve(json.content) return await res.json()
})
.then((res) => {
resolve(res.content)
})
.catch((e) => {
reject(e)
})
}) })
} }