Skip to content

Commit

Permalink
fix(blockchain-link): CustomError with message passed as code
Browse files Browse the repository at this point in the history
  • Loading branch information
szymonlesisz committed Dec 12, 2024
1 parent da0bb0f commit 1824969
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
28 changes: 17 additions & 11 deletions packages/blockchain-link-types/src/constants/errors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const PREFIX = 'blockchain_link/';

const ERROR: { [key: string]: string | undefined } = {
connect: undefined,
worker_not_found: 'Worker not found',
worker_invalid: 'Invalid worker object',
worker_timeout: 'Worker timeout',
Expand All @@ -19,23 +20,28 @@ export class CustomError extends Error {

message = '';

constructor(code: string, message = '') {
constructor(codeOrMessage: string, message = '') {
// test reports that super is not covered, TODO: investigate more
super(message);

this.message = message;

if (typeof code === 'string') {
const c =
code.indexOf(PREFIX) === 0 ? code.substring(PREFIX.length, code.length) : code;
this.code = `${PREFIX}${c}`;
const msg = ERROR[c];
if (typeof msg === 'string') {
if (this.message === '') {
this.message = msg;
} else if (message.indexOf('+') === 0) {
this.message = `${msg} ${message.substring(1)}`;
if (typeof codeOrMessage === 'string') {
const isPrefixed = codeOrMessage.indexOf(PREFIX) === 0;
const code = isPrefixed ? codeOrMessage.substring(PREFIX.length) : codeOrMessage;
const knownCode = Object.keys(ERROR).includes(code);
if (isPrefixed || knownCode) {
this.code = `${PREFIX}${code}`;
const codeMessage = ERROR[code];
if (codeMessage) {
if (this.message === '') {
this.message = codeMessage;
} else if (message.indexOf('+') === 0) {
this.message = `${codeMessage} ${message.substring(1)}`;
}
}
} else if (this.message === '') {
this.message = code;
}
}

Expand Down
8 changes: 4 additions & 4 deletions packages/blockchain-link/tests/unit/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ describe('Custom errors', () => {
expect(error.message).toBe('Worker not found');
});

it('Error with custom code and custom message', () => {
it('Error with custom prefixed code and custom message', () => {
const error = new CustomError('blockchain_link/custom', 'Custom message');
expect(error.code).toBe('blockchain_link/custom');
expect(error.message).toBe('Custom message');
});

it('Error with custom code and without message', () => {
it('Error with custom code as message', () => {
const error = new CustomError('custom');
expect(error.code).toBe('blockchain_link/custom');
expect(error.message).toBe('Message not set');
expect(error.code).toBe(undefined);
expect(error.message).toBe('custom');
});

it('Error without code and with custom message', () => {
Expand Down

0 comments on commit 1824969

Please sign in to comment.