A robust Error subclass with error codes, typed debug values, and recursive
stack traces using native Error.cause.
Usage
First, require me where you could throw errors:
import YError from 'yerror';
Then, emit errors with a bonus: parameters!
function doSomething(pay, action) { if (parseInt(pay, 10) !== pay) { throw new YError('E_BAD_PAY', [pay, action]); }}doSomething('nuts', 'code');// YError: E_BAD_PAY (["nuts", "code"])// at doSomething (/home/nfroidure/nfroidure/yerror/test.js:5:11)// at Object.<anonymous> (/home/nfroidure/nfroidure/yerror/test.js:9:1)// (...)
You don't have to use constant like error messages, we use this convention
mainly for i18n reasons.
Also, you could want to wrap errors and keep a valuable stack trace:
function doSomethingAsync(pay, action) { return new Promise(function (resolve, reject) { try { doSomething(pay, action); resolve(); } catch (err) { reject(YError.bump(err)); } });}doSomethingAsync('nuts', 'code').catch(function (err) { console.log(err.stack);});// YError: E_BAD_PAY (nuts, code)// at doSomething (/home/nfroidure/nfroidure/yerror/test.js:5:11)// (...)// Caused by: YError: E_BAD_TRANSACTION (pay)// at Function.YError.wrap (/home/nfroidure/nfroidure/yerror/src/index.js:41:12)// at /home/nfroidure/nfroidure/yerror/test.js:16:21
Global Error Registry
You can now get full autocompletion and type-safety for your error codes and
their debug data.
import { YError } from 'yerror';declare module 'yerror' { interface YErrorRegistry { E_USER_NOT_FOUND: [userId: string]; }}// TypeScript will now enforce the correct arguments:throw new YError('E_USER_NOT_FOUND', ['123']);// Users of you own code will then be able to cast errorstry { getUser('123');} catch (err) { if (hasYErrorCode(err, 'E_USER_NOT_FOUND')) { console.log(err.debug[0]);