Skip to content

Commit

Permalink
fix: implement custom ts error localy
Browse files Browse the repository at this point in the history
  • Loading branch information
tabaktoni committed Apr 3, 2023
1 parent 70ca3bc commit fa90a3e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
9 changes: 0 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@
"lossless-json": "^2.0.8",
"micro-starknet": "^0.2.1",
"pako": "^2.0.4",
"ts-custom-error": "^3.3.1",
"url-join": "^4.0.1"
},
"lint-staged": {
Expand Down
35 changes: 34 additions & 1 deletion src/provider/errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
// eslint-disable-next-line max-classes-per-file
export function fixStack(target: Error, fn: Function = target.constructor) {
const { captureStackTrace } = Error as any;
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
captureStackTrace && captureStackTrace(target, fn);
}

export function fixProto(target: Error, prototype: {}) {
const { setPrototypeOf } = Object as any;
// eslint-disable-next-line @typescript-eslint/no-unused-expressions, no-proto, no-param-reassign
setPrototypeOf ? setPrototypeOf(target, prototype) : ((target as any).__proto__ = prototype);
}

/* eslint-disable max-classes-per-file */
import { CustomError } from 'ts-custom-error/dist/custom-error';
export class CustomError extends Error {
name!: string;

constructor(message?: string) {
super(message);
// set error name as constructor name, make it not enumerable to keep native Error behavior
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target#new.target_in_constructors
// see https://github.com/adriengibrat/ts-custom-error/issues/30
Object.defineProperty(this, 'name', {
value: new.target.name,
enumerable: false,
configurable: true,
});
// fix the extended error prototype chain
// because typescript __extends implementation can't
// see https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
fixProto(this, new.target.prototype);
// try to remove contructor from stack trace
fixStack(this);
}
}

export class LibraryError extends CustomError {}

Expand Down

0 comments on commit fa90a3e

Please sign in to comment.