Siecje
Siecje

Reputation: 3712

How to handle an error in beforeCreate?

I'm trying to validate that a foreign key exists. I only want to create an object if the foreign key is valid.

I am querying for the object in beforeCreate but when I call the callback with an error message the error is not handled (traceback) and a 500 is returned.

I would like to handle the error gracefully and return a 400 (Bad Request) status code.

  beforeCreate: function(values, next) {
    // Verify that the brand id is valid
    Brand.findOne(values.brand, function(err, brand){
      if (err || !brand){
        return next({"error": "Brand does not exist."});
      }
      return next();
    });
  }

Upvotes: 4

Views: 824

Answers (3)

iamonuwa
iamonuwa

Reputation: 91

I know this is a late post.

Here is my solution

ModelError.js

module.exports = function(message, code) {
let err = new Error();
err.name = 'Validation';
err.code = {
    code: code,
    message: message
}
err.invalidAttributes = {};
err.message = message;

return err;
}

Model.js

beforeCreate: function (values, next) {
    Model.find(values.id)
        .then(function(result) {
            if (typeof result !== 'undefined') {
                next();
            } else {
                next(ModelError('Not Found', 404));
            }
        }).catch(function(err) {
            next(ModelError(err, 500));
        });
}

ExampleController.js

create: (req, res) {
    Model.create(req.body, function(err, response) {
        if (err) {
            // I have my own custom response file
            return Response.json(err.code.code, res, err.message);
        } else {
            return Response.json(201, res, 'Created', response);
        }
    })
}

Upvotes: 0

Bruno Haveroth
Bruno Haveroth

Reputation: 1

I solved it this way:

Create a Sails Service ModelError.js

module.exports = function(message, code) {
    var err = new Error();
    err.name = 'Validation';
    err.code = (code ? code : 400);
    err.invalidAttributes = {};
    err.message = message;

    return err;
};

In the Model beforeCreate

beforeCreate: function(record, cb) {
  if (found) return cb(ModelError('message error!!!!!!!!', 400));
  return cb();
}

And subscribe the response/negotiate.js

module.exports = function negotiate(data) {
  // Get access to `req`, `res`, & `sails`
  var req = this.req;
  var res = this.res;
  var sails = req._sails;

  // Set status code
  res.status((data.code ? data.code : 400));

  // Log error to console
  if (data !== undefined) {
    sails.log.verbose('Sending negotiate response: \n',data);
  }
  else sails.log.verbose('Sending negotiate response');
  // console.log(data.Errors)
  if(data.Errors) return res.jsonx({errors: data.Errors});
  if(data.message) return res.jsonx(data.message)
  return res.jsonx(data)
};

Any error automatically called by the sails drops in the negotiate.js, so just treat the same to return the error code based on the data.code.

Upvotes: 0

Sachacr
Sachacr

Reputation: 732

I'm not sure but what happen if you do :

return next(new Error("Brand does not exist."));

Upvotes: 1

Related Questions