Thalatta
Thalatta

Reputation: 4578

How to construct a non-custom error by Hand in Sails.js

I am writing a Service to be used by my Controllers in my Sails.js application.

If an error is thrown in the Service, I would like to return a error. I am used to the syntax of function callback(err, bar){ if (err) return error}. I am in a slightly different case, though. In the following code

function callBack(err, uploadedFiles){
    if (err) return err;
    if (uploadedFiles.length == {
       return foo; //This is what needs to be of type "err"
    } 
});
}
}

So do I create a JSON object like

return { error: "error", message: 404}

I am not sure how to do this.

Upvotes: 0

Views: 55

Answers (3)

Anthony Yuen
Anthony Yuen

Reputation: 166

You can raise your 404 error in your Services like this (assuming your service needs to work asynchronously):

var err = new Error('your message');
err.status = 404; // could be other HTTP status
return cb(err);

And in your calling function, you can handle the error like this:

SomeServices.somefunction(options, function (err, data) {
  // res.negotiate(err) will automatically trigger res.notFound if err.status is 404
  if (err) return res.negotiate(err); 
  /* your logic if not 404 */
}

The codes are quite simple here. Is that what you want?

Upvotes: 0

Rakesh
Rakesh

Reputation: 66

Why are you not using sails functions for responses? I am also new so excuse me if said something silly.

If you want to send a 404 status code which is for Not Found errors the you can use sails provided response res.notFound() like this:

return res.notFound({
    message: "Some Message Here"
});

If you want to show completely custom message without any status code like 404 then use send() instead like this:

return res.send({
    status: "404 or anything you like",
    message: "Some Message Here"
});

Sorry, res.send() will also generate a status code but it will be 200 which means OK, so its a success code.

Upvotes: 1

Thalatta
Thalatta

Reputation: 4578

I believe it is:

{success:false, error: err}

Upvotes: 0

Related Questions