forked from badges/shields
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror-helper.js
67 lines (62 loc) · 1.72 KB
/
error-helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict'
const {
NotFound,
InvalidResponse,
Inaccessible,
} = require('../services/errors')
const defaultErrorMessages = {
404: 'not found',
}
const checkErrorResponse = function(badgeData, err, res, errorMessages = {}) {
errorMessages = { ...defaultErrorMessages, ...errorMessages }
if (err != null) {
badgeData.text[1] = 'inaccessible'
badgeData.colorscheme = 'red'
return true
} else if (errorMessages[res.statusCode] !== undefined) {
badgeData.text[1] = errorMessages[res.statusCode]
badgeData.colorscheme = 'lightgrey'
return true
} else if (res.statusCode !== 200) {
badgeData.text[1] = 'invalid'
badgeData.colorscheme = 'lightgrey'
return true
} else {
return false
}
}
checkErrorResponse.asPromise = function(errorMessages = {}) {
return async function({ buffer, res }) {
errorMessages = { ...defaultErrorMessages, ...errorMessages }
if (res.statusCode === 404) {
throw new NotFound({ prettyMessage: errorMessages[404] })
} else if (res.statusCode !== 200) {
const underlying = Error(
`Got status code ${res.statusCode} (expected 200)`
)
const props = { underlyingError: underlying }
if (errorMessages[res.statusCode] !== undefined) {
props.prettyMessage = errorMessages[res.statusCode]
}
if (res.statusCode >= 500) {
throw new Inaccessible(props)
}
throw new InvalidResponse(props)
}
return { buffer, res }
}
}
async function asJson({ buffer, res }) {
try {
return JSON.parse(buffer)
} catch (err) {
throw new InvalidResponse({
prettyMessage: 'unparseable json response',
underlyingError: err,
})
}
}
module.exports = {
checkErrorResponse,
asJson,
}