@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
73 lines (67 loc) • 2.93 kB
JavaScript
module.exports = {
pruneErrors
};
function pruneErrors() {
function stacklessError(message) {
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error(message);
Error.stackTraceLimit = stackTraceLimit;
return error;
}
require('axios').interceptors.response.use(
response => response,
axError => {
const { inspect } = require('util');
let { url, method } = axError.config ?? {};
url = url?.replace(/(passcode|refreshToken|clientsecret|key)=[^&]+/g, '$1=...');
const { errno, code, response = {}, message: axMessage } = axError;
const prefix = (url && method ? `${method.toUpperCase()} ${url}` : 'Request') + ' failed';
let error;
if (errno) {
// System error during request.
const message = prefix
+ `: ${errno} ${code}`
+ (/\b(ENOTFOUND|EAI_AGAIN)\b/.test(code) ? `. Make sure the URL is correct and the server is running.` : '');
error = stacklessError(message);
} else {
// Error after request has been made.
const { status, statusText } = response;
let { data } = response;
if (Buffer.isBuffer(data)) {
data = data.toString();
try {
data = JSON.parse(data);
} catch (error) { /* unexpected; data will be included in error below */
}
}
const inspectData = data && !data.error_description;
const reason = !inspectData && data?.error /* RFC 6749 */ && (typeof data.error === 'string' ? data.error : inspect(data.error));
const details = inspectData ? inspect(data) : data?.error_description /* RFC 6749 */;
const message = prefix + (
status || statusText || reason || details
? (status || statusText ? ':' : '') +
(status ? ` ${status}` : '') +
(statusText ? ` ${statusText}` : '') +
(reason ? `. ${reason}` : '') +
(details ? `. Details: ${details}` : '')
: (axMessage ? `: ${axMessage}` : '')
);
error = stacklessError(message);
if (status) {
error.status = status;
}
if (data?.passcode_url) {
error.auth = {
passcode_url: data.passcode_url
};
}
}
if (require('../').debug('req')) {
error.cause = axError;
}
return Promise.reject(error);
}
);
return module.exports;
}