javascript / expert
Snippet
Custom Operational Error Abstractions via Error.captureStackTrace
Custom error classes extending Error often include internal constructor invocation frames in stack traces, cluttering error logs. Node.js provides V8's Error.captureStackTrace API to dynamically strip unwanted internal constructor stack frames while distinguishing operational errors from uncaught programmer bugs.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
export class AppError extends Error {constructor(message, statusCode, isOperational = true) {super(message);this.name = this.constructor.name;this.statusCode = statusCode;this.isOperational = isOperational;Error.captureStackTrace(this, this.constructor);}}
nodejs
Breakdown
1
export class AppError extends Error {
Defines a base application error extending the standard Error prototype.
2
this.name = this.constructor.name;
Sets the error name dynamically to the concrete class name.
3
Error.captureStackTrace(this, this.constructor);
Omits the constructor call from the stack trace for clean error reporting.