javascript / intermediate
Snippet
Cleaning Stack Traces in Custom Errors
In Node.js (V8), Error.captureStackTrace allows you to hide the internal implementation details of your custom error classes from the stack trace, making logs cleaner and more relevant to the caller.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
class DatabaseError extends Error {constructor(message, query) {super(message);this.query = query;if (Error.captureStackTrace) {Error.captureStackTrace(this, DatabaseError);}}}throw new DatabaseError('Connection lost', 'SELECT * FROM users');
nodejs
Breakdown
1
Error.captureStackTrace(this, DatabaseError);
Captures the stack trace but excludes the constructor of DatabaseError from the output.