try

Error

handling

Long time ago

function foobar() {
    throw Error('Omg something happend');
}

A bit later

const errors = {
    NO_USER: 'There is no such user',
    NO_CONNECTION: 'Database connections is closed',
};

function foobar(cb) {
    cb(errors.NO_USER);
}

foobar(function(err, res) {
    if (err) {
        console.log(err); 
        return;
    }
    // oh yeah no errors
});

PROS

  • easy to create errors
  • traceable errors
  • easy to use

CONS

  • no instanceof
  • no context information
  • not Error sublclass
  • no error cause

What's the problem

with extending Error

The SOLution

Node-errors-helpers

const { createErrorClass } = require('errors-helpers');

const AppError = createErrorClass(
  'AppError',
  'Error in application',
  Error // parent error class, optional 
);

What you can

/* AppError is our custom error class */

const RuntimeError = createErrorClass(
    'RuntimeError', 
    'Runtime error', 
    AppError
);

const cause = new Error();
cosnt e = new RuntimeError(extraData, cause);

e instanceof AppError === true
e instanceof Error === true

check instanceof

What you can

/* AppError is our custom error class */
const { 
    hasErrorClass 
} = require('errors-helpers').helpers;

const RuntimeError = createErrorClass(
    'RuntimeError', 
    'Runtime error', 
    AppError
);

const cause = new Error();
const e = new RuntimeError(extraData, cause);

// checks all causeBy recursively
hasErrorClass(e, Error) === true

check caused by

What you can

/* AppError is our custom error class */
const { 
    getFullName 
} = require('errors-helpers').helpers;

const RuntimeError = createErrorClass(
    'RuntimeError', 
    'Runtime error', 
    AppError
);

const cause = new Error();
const e = new RuntimeError(extraData, cause);

// checks all causeBy recursively
getFullName(e) === 'Error.AppError.RuntimeError'

GET FULL NAME

What you can

/* AppError is our custom error class */
const { 
    getObject 
} = require('errors-helpers').helpers;

const RuntimeError = createErrorClass(
    'RuntimeError', 
    'Runtime error', 
    AppError
);

const e = new RuntimeError({ lol: 'kek' });

getObject(e);

/* { 
    name: 'RuntimeError', 
    message: 'RuntimeError
    data: { lol: 'kek' },
    causedBy: null,
    stack: '...',
} */

GET JSON of error

What you can

/* AppError is our custom error class */
const { 
    createErrorsList 
} = require('errors-helpers').helpers;

const errors = createErrorsList({
    BestError: 'This is best error message',
    OmgError: 'This is OMG error', 
}, AppError);

const e = new errors.BestError({ lol: 'kek' });

e instanceof AppError === true

Create list of errors

And one more

It

Works in browser

you are welcome to use node-errors-helpers

That's all folks

Made with Slides.com