Skip to content

Commit

Permalink
Added error chaining
Browse files Browse the repository at this point in the history
  • Loading branch information
CMCDragonkai committed Dec 3, 2021
1 parent bc6283b commit 5172d01
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 31 deletions.
55 changes: 25 additions & 30 deletions src/DB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,44 +126,39 @@ class DB {
recursive: true,
});
} catch (e) {
throw new errors.ErrorDBDelete(e.message, {
errno: e.errno,
syscall: e.syscall,
code: e.code,
path: e.path,
});
throw new errors.ErrorDBDelete(e.message, undefined, e);
}
}
try {
await this.fs.promises.mkdir(this.dbPath);
} catch (e) {
if (e.code !== 'EEXIST') {
throw new errors.ErrorDBCreate(e.message, {
errno: e.errno,
syscall: e.syscall,
code: e.code,
path: e.path,
});
throw new errors.ErrorDBCreate(e.message, undefined, e);
}
}
const dbLevel = await new Promise<LevelDB<string | Buffer, Buffer>>(
(resolve, reject) => {
const db = level(
this.dbPath,
{
keyEncoding: 'binary',
valueEncoding: 'binary',
},
(e) => {
if (e) {
reject(e);
} else {
resolve(db);
}
},
);
},
);
let dbLevel;
try {
dbLevel = await new Promise<LevelDB<string | Buffer, Buffer>>(
(resolve, reject) => {
const db = level(
this.dbPath,
{
keyEncoding: 'binary',
valueEncoding: 'binary',
},
(e) => {
if (e) {
reject(e);
} else {
resolve(db);
}
},
);
},
);
} catch (e) {
throw new errors.ErrorDBCreate(e.message, undefined, e);
}
this._db = dbLevel;
this._running = true;
this.logger.info(`Started ${this.constructor.name}`);
Expand Down
6 changes: 5 additions & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import type { POJO } from './types';

import { CustomError } from 'ts-custom-error';

type ErrorChain = Error & { chain?: ErrorChain };

class ErrorDB extends CustomError {
data: POJO;
constructor(message: string = '', data: POJO = {}) {
cause?: ErrorChain;
constructor(message: string = '', data: POJO = {}, cause?: ErrorChain) {
super(message);
this.data = data;
this.cause = cause;
}
}

Expand Down

0 comments on commit 5172d01

Please sign in to comment.