0

I have a code in node - sails js mongo db code like this, it is for user signup: signup fn:

try{
    let err;
    let user = await User.create({req.body}).fetch();
    if (!user){
      throw new Error('Failed');
    }
    res.status(200).json({user});
  }catch(e){
    res.status(500).json({e.message});
  }
};

req.body:

{

    "firstName": "jay", // required
    "lastName": "Thomas", 
    "email":"yo@gmail.com", // required and unique
    "password": "X12345678", // required
    "languages":["c++", "english"]
}

if I miss-spell the email to emal, it should through a db error which it does and sends the response, but it also shows the error on the console, which I do not want. I only want it to send the error in response. What changes I need for that?

Vinita
  • 1,834
  • 2
  • 8
  • 20

1 Answers1

1

Instead of using res.status may I suggest the built in responses Sails provides out of the box? Sails handles responses very well via in built response functions such as return res.serverError(err) or return res.badRequest(err) for example.

If you look inside your /api/responses path you should see a file named "serverError.js" - which matches your 500 status code response.

https://github.com/balderdashy/sails/blob/master/lib/hooks/responses/defaults/serverError.js

In this file (on line 35 for me on the latest version of Sails.js) there is this line:

// Log error to console
sails.log.error('Sending 500 ("Server Error") response: \n', flaverr.parseError(data) || data);

This indicates the intention to log any errors to the console or a file by default which is best practice for error logging.

If you need to ignore errors you can either edit these response files to remove default console logging, you change your log level to ignore ERRORS (not recommended) or you attempt to intercept them and handle them gracefully in your own way, the way to do this can be seen at this place:

https://sailsjs.com/documentation/concepts/models-and-orm/errors#?negotiating-errors-with-await

MattGarnett
  • 545
  • 3
  • 20