Manage errors in Restify
Asked Answered
G

2

18

How i can manage all error of my restful server build with Restify of NodeJS? For example internal errors, database errors, validate, required params, not founds, athorizeds... And uncaughtException and return custom response to browser?

How i can design the share of data and errors between controllers?

Thanks

Garboil answered 17/8, 2013 at 0:31 Comment(0)
U
31
  1. Handle your errors immediately, where they're generated. next(err) really means res.send(err). It's not an alternative to throw err. If you need to log and shut down, pass it off to an error handling module instead of stuffing it in next(err) where it will be swallowed.
  2. server.on('uncaughtException'... is how you handle any errors that were thrown in middleware / routes. It works fine for that purpose, as long as you remember the first guideline. 'uncaughtException' will not be triggered for next(err) calls.
  3. formatters are the way to customize error messages going out to the users. They're definitely not a viable alternative to dealing with errors in uncaughtException, because presumably, once you get there, you're sending the user the error you want them to see... not necessarily the error that was originally generated. See point 1.
  4. For errors unrelated to middleware, remember to use process.on('uncaughtException'...
Uncouth answered 15/3, 2014 at 3:22 Comment(1)
Thanks for writing such a helpful overview, one which would improve the restify docs IMHO.Distributive
J
0
const errs = require('restify-errors');
module.exports = (validator) => {
  return (req, res, next) => {
    if (req.body && req.body !== undefined) {
      const { error } = validator(req.body);
      if (error) {
        let errors = {};
        error.details.forEach((err) => {
          errors = { ...errors, [err.context.key]: err.message };
        });

        res.send(422, { ...new errs.UnprocessableEntityError('Validation error').body, error: errors })
        return next(new Error)
      }
      return next();
    } else {
      return next(new errs.UnprocessableEntityError("No data provided."))
    }
  };
};
Juggler answered 14/11, 2021 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.