Reputation: 1190
I have been able to easily set up a basic node.js api with the help of strongloop. I have been able to add custom routes using remoteMethods
. However, I am a bit confused in setting up 404
for those routes. I have one route for model category
named mature
that takes one argument(categorId
) and fetches all games under that category that have boolean value set to true for mature
. The endpoint url is: http://localhost:3000/api/Categories/1004/games/mature
. If I place a non existent categorId
, it breaks. What would be the best way to setup routes to handle 404
for errors? For example, display "no such category id"
. Github REPO
common/models/category.js
Category.mature = function(id, limit) {
var app = this.app;
var Games = app.models.Games;
Category.findById(id, {}, function(err, category){
if (err) return callback(err);
//set limit
if (limit && limit > 5){
limit = 5;
}else if(limit === undefined){
limit = 5;
}
Games.find({
"where": {
categoryId: id,
mature: true,
gameId: {gt: hashids.decode(after)}
},
"limit": limit
}, function(err, gameArray) {
if (err) return callback(err);
callback(null, gameArr);
});
)};
Category.remoteMethod(
'mature', {
accepts: [
{arg: 'id', type: 'number', required: true},
{arg: 'limit',type: 'number',required: false}
],
// mixing ':id' into the rest url allows $owner to be determined and used for access control
http: {
path: '/:id/games/mature',
verb: 'get'
},
returns: {
root: true,
type: 'object'
}
}
);
};
Upvotes: 0
Views: 203
Reputation: 3396
Set err.statusCode
to 404 before you call callback(err)
:
if(!category) {
var err = new Error('Category ID ' + id + ' does not exist.');
err.statusCode = 404;
callback(err);
}
This will result in:
Upvotes: 2