Prevent printing js errors attached fields

If you log a NodeJs error in the console it will also show all the fields attached, this is a problem if errors are very long as they will make a mess in your terminal of CI. Fortunately there is a way to hide them.
profile photo
Tommy
If you log a NodeJs error in the console it will also show all the fields attached, this is a problem for very long fields as they will make a mess in your terminal of CI.
For example having this custom error class:
typescript
export class ShellError extends Error { stdout: string stderr: string output: string constructor(message: string, stdout: string, stderr: string) { super(message) this.stdout = stdout this.stderr = stderr this.output = stdout + '\n' + stderr } } console.log(new ShellError('error', 'stdout', 'stderr'))
The console will show
shell
ShellError: error at Object.<anonymous> (/Users/morse/Documents/GitHub/docs-from-notion/local-scripts/play.ts:17:13) at Module._compile (node:internal/modules/cjs/loader:1103:14) at Object.m (/Users/morse/.volta/tools/image/packages/esno/lib/node_modules/esno/node_modules/@esbuild-kit/cjs-loader/dist/index.js:1:536) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:168:29) at ModuleJob.run (node:internal/modules/esm/module_job:197:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:337:24) at async loadESM (node:internal/process/esm_loader:88:5) { stdout: 'stdout', stderr: 'stderr', output: 'stdout\nstderr' }
As you can see it shows the fields stdout and stderr. This is a big problem if these fields are very big because it will hide everything else in the console.
Fortunately there is a solution, you can use js private fields to hide the fields from NodeJs and add getters to allow retrieving them by your code:
typescript
export class ShellError extends Error { #stdout: string #stderr: string #output: string constructor(message: string, stdout: string, stderr: string) { super(message) this.name = 'ShellError' this.#stdout = stdout this.#stderr = stderr this.#output = stdout + '\n' + stderr } get output() { return this.#output } }
Private fields are fairly new in javascript so you will need to transpile them away or use latest NodeJs.
fields that start with # are called private fields and are not accessible outside of the class, that’s why we created the get output getter
Related posts
Building Docker images without installing deps by using a bundler
post image
I used Notaku to create this site. Want to know more? Click on the link silly
Powered by Notaku