@sap-cloud-sdk/util
Version:
SAP Cloud SDK for JavaScript general utilities
69 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorWithCause = void 0;
exports.isErrorWithCause = isErrorWithCause;
const logger_1 = require("./logger");
const logger = (0, logger_1.createLogger)({
package: 'util',
messageContext: 'error-with-cause'
});
/**
* Represents an error that was caused by another error.
*/
class ErrorWithCause extends Error {
/**
* Create an instance of ErrorWithCause.
* @param message - Error message.
* @param cause - Original error, causing this error.
*/
constructor(message, cause) {
// There is an issue with the prototype chain when extending from Error: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
super(message); // 'Error' breaks prototype chain here
this.cause = cause;
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
this.name = 'ErrorWithCause';
this.addStack(cause);
}
isAxiosError(err) {
return 'isAxiosError' in err && err.isAxiosError === true;
}
addStack(cause) {
// Axios removed the stack property in version 0.27 which gave no useful information anyway. This adds the http cause.
if (this.isAxiosError(cause)) {
let response = '';
if (cause.response?.data) {
try {
response = `\n${JSON.stringify(cause.response?.data, null, 2)}`;
}
catch (error) {
logger.warn(`Failed to stringify response data: ${error.message}`);
response = `\n${cause.response?.data}`;
}
}
this.stack = `${this.stack}\nCaused by:\nHTTP Response: ${cause.message}${response}`;
}
else if (this.stack && cause?.stack) {
// Stack is a non-standard property according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
this.stack = `${this.stack}\nCaused by:\n${cause.stack}`;
}
}
/**
* Root cause of the error.
* If there are multiple errors caused one by another, the root cause is the first error that occurred.
* In case there is no root cause.
* @returns The root cause.
*/
get rootCause() {
return isErrorWithCause(this.cause) ? this.cause.rootCause : this.cause;
}
}
exports.ErrorWithCause = ErrorWithCause;
/**
* Type guard to check whether an error is of type ErrorWithCause.
* @param err - An error.
* @returns Whether the given error is of type ErrorWithCause.
*/
function isErrorWithCause(err) {
return err?.name === 'ErrorWithCause';
}
//# sourceMappingURL=error-with-cause.js.map