neumino / thinky

JavaScript ORM for RethinkDB
http://justonepixel.com/thinky/
Other
1.12k stars 128 forks source link

Feature Idea: Model names in errors #613

Open adammcarth opened 7 years ago

adammcarth commented 7 years ago

Since we store the name of a model when it's defined:

let Vegetable = thinky.createModel("Vegetable", { // <--
  id: type.string(),
  name: type.string().required()
});

...wouldn't it make sense to improve our custom error messages to use that name? For instance (and the most practical example), when a document can't be found - I think "The Vegetable couldn't be found." is a much clearer error message than "The query did not find a document and returned null.". This would be particularly useful when you have multiple chained lookups, and you need to know which of them couldn't be found:

Fruit.get(req.params.fruitId).then(() => {
  Vegetable.get(req.params.vegetableId).then(() => {
    Candy.get(req.params.candyId).then(() => {
      return res.json({message: "Everything was found! :)"});
    }).error(next);
  }).error(next);
}).error(next);

Anyone else think this feature would be a good idea? I started looking at /lib/errors.js, but I'm not sure how we could access the actual model attributes from that class 🙁 .

adammcarth commented 7 years ago

Update: This would of course only apply to Thinky error messages, not errors from the RethinkDB driver. The way I currently do it is similar to the following code, but it's not ideal:

// vegetable.js
Vegetable.get("1").error(e=>{e.model="Vegetable";next(e);});
// server.js (error handler)
app.use((err, req, res, next) => {
  if ( err.name === "DocumentNotFoundError" ) {
    if ( err.model ) {
      err.name = err.model + "NotFound";
      err.message = "Couldn't find that " + err.model;
    }

    console.log(err);
    // => { name: "VegetableNotFound", message: "Couldn't find that Vegetable." }
  }
});

This is why I thought something built-in might be useful.