node.js - How to produce errors\exceptions in callback functions in mongoose for testing purpose -
i working mongodb using mongoose. of opeartion works callback. error may occur while saving/updating/finding document. though can check if there error in callback function (as shown in below code) want know while developing how can generate error , test these blocks?
tank.findbyid(id, function (err, tank) { if (err) return handleerror(err); tank.size = 'large'; tank.save(function (err) { if (err) return handleerror(err); res.send(tank); }); });
are familiar error
class? emiting errors eventemitter
? throwing errors throw
?
this link extensive overview on how deal errors in node.
assuming using express, in case of example provided, create instance of error
class doing like:
exports.findtankbyid = function(req, res, next) { var id = req.params.id; tank.findbyid(id, function (err, tank) { if (err) { var e = new error("failed find tank"); e.data = err; // attach other useful data error class instance return next(e); } return res.status(200).json({ data: tank }); }) });
then in part of application, have middleware function catches errors passed routes via next()
. function log error or doing more creative. note when using new error(...)
can access stack using stack attribute of error
class (e.g. err.stack
). after processing error, error handler function send appropriate response.
a simple error handler function like:
app.use(function (err, req, res, next) { if(err.data) { // caught operational errors /* log or process error */ var response = { type : 'error', description : err.message // use "failed tank" above example }; res.status(500).json(response); } else { // unexpected errors var domainthrown = err.domain_thrown || err.domainthrown; var msg = 'domainthrown: ' + domainthrown + '\n' + err.stack; console.error('%s %s\n%s', req.method, req.url, msg); res.set('connection', 'close'); res.setheader('content-type', 'text/plain'); res.status(503).send(msg + '\n'); } });
if approach, define more specific error objects of own more or less extend error
class. using functions create more specific error types limits need write out the
var e = new error("failed find tank"); e.data = err; /* attach other useful data error class instance */
part every time. using more specific error objects forces consistency on how errors being formatted. hope helpful,
craig
Comments
Post a Comment