Created
February 11, 2024 16:29
-
-
Save dgolosov/1070697964675b348d507b694ec874fd to your computer and use it in GitHub Desktop.
Exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AppError extends Error { | |
constructor(message, data, options) { | |
super(message, options); | |
this.name = this.constructor.name; | |
this.data = data; | |
if (options && options.cause) { | |
const stackOffset = (this.message.match(/\n/g) || []).length + 2; | |
const afterCauseStack = this.stack | |
.split("\n") | |
.slice(0, stackOffset) | |
.join("\n"); | |
this.stack = afterCauseStack + "\n" + options.cause.stack; | |
} | |
} | |
} | |
class OrderError extends AppError { | |
get customerId() { | |
return this.data.customerId; | |
} | |
} | |
const processOrder = (details) => { | |
const tokenizeCard = () => { | |
throw new Error("Card tokenization failed"); | |
}; | |
const pay = () => tokenizeCard(); | |
try { | |
pay(); | |
} catch (e) { | |
throw new OrderError("Could not process order", details, { cause: e }); | |
} | |
}; | |
try { | |
// ... | |
processOrder({ customerId: 123 }); | |
// ... | |
} catch (e) { | |
if (e instanceof OrderError) { | |
console.error(e); | |
console.debug(`Could not process order for customer ${e.customerId}`); | |
} | |
// ... | |
throw e; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment