dimanche 20 avril 2014

Handling errors between two layers in javascript


Vote count:

0




I have a node.js app Using express and 3 layers (controllers, api and models).


The controller asks the API layer to post, edit or add objects (promise styled). The API validates and executes the request (using the model layer (mongoose)). the controller must tells the client whether his request has been accepted or not. Here is a small schema by rendering error page or flash messages.


app structure chart


Here is a piece of example:



Controller:

exports.doEdit = function(req, res) {
var args;
args = req.body;
return app.api.mods.edit(req.getUserId(), req.params.id, args.name, args.value).then(function(status) {
return res.send(200, "Saved!");
}).fail(function(err) {
return res.send(400, err.message);
});
};

API Layer:

/*
Edit a mod
@param userid the current logged user id
@param slug the slug of the mod
@param field the field to be edited
@param value the new value
@permission mod:edit
*/


exports.edit = (function(userid, slug, field, value, callback) {
return canThis(userid, "mod", "browse").then(function(can) {
var Mod;
Mod = mongoose.model("Mod");
return Mod.findOne({
slug: slug
}, function(err, mod) {
if (can === false && mod._id !== userid) {
return callback(new Error("unauthorized"));
}
if (err || !mod) {
if (err) {
console.log(err);
}
return callback(new Error("Please try again"));
}
mod[field] = value;
mod.save();
return callback("ok");
});
});
}).toPromise(this);


How to makes easy, flexible and clean communication for the errors ?


I thought of adding a JSON object like that



{
status: "error",
code: "404",
id: "not_found",
message: "Not found"
}


But how to add it to the error that takes only a message? And Is it flexile and "clean"?



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire