Make a clear distinction between programmer errors ("internal errors") and runtime errors, and allow configuring the server to let the programmer errors bubble up in development and unit testing. This saves a huge amount of time because it generates ordinary stack traces when things go wrong. And, if these errors occur in production, we'll catch them, and display **shields | internal error** which is the equivalent of a 500 error.
50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
'use strict';
|
|
|
|
const {
|
|
NotFound,
|
|
InvalidResponse,
|
|
} = require('../services/errors');
|
|
|
|
const checkErrorResponse = function(badgeData, err, res, notFoundMessage = 'not found') {
|
|
if (err != null) {
|
|
badgeData.text[1] = 'inaccessible';
|
|
badgeData.colorscheme = 'red';
|
|
return true;
|
|
} else if (res.statusCode === 404) {
|
|
badgeData.text[1] = notFoundMessage;
|
|
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 ({ notFoundMessage } = {}) {
|
|
return async function ({ buffer, res }) {
|
|
if (res.statusCode === 404) {
|
|
throw new NotFound(notFoundMessage);
|
|
} else if (res.statusCode !== 200) {
|
|
const underlying = Error(`Got status code ${res.statusCode} (expected 200)`);
|
|
throw new InvalidResponse(undefined, underlying);
|
|
}
|
|
return { buffer, res };
|
|
};
|
|
};
|
|
|
|
async function asJson({ buffer, res }) {
|
|
try {
|
|
return JSON.parse(buffer);
|
|
} catch (err) {
|
|
throw new InvalidResponse();
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
checkErrorResponse,
|
|
asJson,
|
|
};
|