error-agent

a simple error handler

error agent is a module help you deal with the errors, and respond them to http client

npm install error-agent

when dealing with errors, many people simply use string, instead of Error object, which is not appropiate

you need to use Error object, attached with some properties, so you know how to deal with it later

so, when you're in async code

var errorAgent= require('error-agent');
 
DB.queryUser(function(erruserData){
    if(!userData.auth) //if this user is not authenticated to read this page 
        callback( errorAgent.handle({ status: 403, msg: 'you need to sign in to see' }) )  //callback an error 
})

or simply throw

if(!userData.auth)
    throw errorAgent.handle({ status: 403, msg: 'you need to sign in to see' });

as you might guess, errorAgent.handle return an Error object with the properties you pass in

you should call it at your last callback

and pass the error object to use, pass req, res to send

it will deal with it for you

errorAgent.send(err, req, res);

you can use code property, so you can register a function to deal with certain error code

if(user.hasNoName)
    throw errorAgent.handle({code: 'USER_NONAME'});

register a code error handler first

ErrorAgent.register('USER_NONAME', function (reqres) {
    res.send('you got no name!');
});

just give a file path, that will exports error code handlers

would be better

ErrorAgent.config({ codesPath: __dirname + '/errors.js' })

see here

  • error page folder path