Note that there are some explanatory texts on larger screens.

plurals
  1. PORestFul Api Node.js & Mongoose: handling errors
    text
    copied!<p>I want to create a restful API with Node.js, Express, MongoDB and Mongoose.</p> <p>Schema, model and route are below:</p> <pre><code>// Schema var OperatorSchema = new Schema({ name : { type: String, unique: true , required: true}, short_name : { type: String, unique:true, required: true }, }); Operator = mongoose.model('Operator', OperatorSchema); // My Api for Operator app.post('/api/operators', common.createOperator); exports.createOperator = function(req, res){ Operator.create(req.body, function (err, operator) { // If failed, return error message if (err) { console.log(err); res.send(404, err) } else { res.send(operator) } }) }; </code></pre> <p>I have three questions:</p> <p><strong>1 -</strong> Handling error like that I found that the err object passed to the callback has a different structure depending if the error comes from mongoose or mongo. </p> <pre><code>// Mongo Error: { "name": "MongoError", "err": "E11000 duplicate key error index: ussdauto.operators.$name_1 dup key: { : \"OpTest\" }", "code": 11000, "n": 0, "connectionId": 231, "ok": 1 } // Mongoose Error: { "message": "Validation failed", "name": "ValidationError", "errors": { "short_name": { "message": "Path `short_name` is required.", "name": "ValidatorError", "path": "short_name", "type": "required" } } } </code></pre> <p>I don't want to expose all the details about errors: only a message explaining the error is enough, no need for to know if it's a mongoerror or a validationError for example. How do you manage it?</p> <p><strong>2 -</strong> The second question is more global: I'll have multiple API and each time I'll need to do the same work: check if there is errors, if some return via API in JSON the error message and if not continue normally. How can I use only one function to process errors and use it everywhere? </p> <p><strong>3 -</strong> I came from a python world (Django in fact) where Tastypie was a really great module which was handling all of that stuff itself. Do you know if such a module exists for Node.js + Express?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload