meteor-restivus
meteor-restivus copied to clipboard
Throw an Meteor.Error instead of Writing the error stack on response
Hi guys, I'm using restivus on my project and it is very good, but I'm trying to understand this part:
https://github.com/kahmali/meteor-restivus/blob/06c62dba369d216aea52e824a1f5bf0f5af61321/lib/route.coffee#L62
try
responseData = self._callEndpoint endpointContext, endpoint
catch error
# Do exactly what Iron Router would have done, to avoid changing the API
ironRouterSendErrorToResponse(error, req, res);
return
Why don't you guys throw an new Meteor.Error() instead of calling ironRouterSendErrorToResponse?
How I got this doubt:
- My goal is to create a validation that will be used on both admin panel and API
- I have a collection called
Products - I created some validations using hooks and schemas like that:
var schema = new SimpleSchema({
_id: { type: String, label: 'ID', },
name: { type: String, label: 'Name', min: 3, max: 200 }
});
Products.before.insert((_userId, _product) => {
const context = schema.newContext();
context.validate(_product);
if (!context.isValid()) {
throw new Meteor.Error(400, 'The product name is invalid');
}
});
Products.before.update(function(_userId, _product, _fields, _modifier) {
const context = schema.newContext();
var product = _.extend({}, _product, _modifier);
context.validate(product);
if (!context.isValid()) {
throw new Meteor.Error(400, 'The product name is invalid');
}
});
- I add this collection to my API like that:
const API = new Restivus({
apiPath: '/api/v1',
enableCors: true,
useDefaultAuth: true,
prettyJson: true,
defaultHeaders: { 'Content-Type': 'application/json' }
});
API.addCollection(Products, { authRequired: true });
But when the my validation fails my app crashes instead of getting a response error like you do at: https://github.com/kahmali/meteor-restivus/blob/06c62dba369d216aea52e824a1f5bf0f5af61321/lib/route.coffee#L159
Is there a way to get a response error instead of writing all the error stack on the response?
I think this code:
try
responseData = self._callEndpoint endpointContext, endpoint
catch error
# Do exactly what Iron Router would have done, to avoid changing the API
ironRouterSendErrorToResponse(error, req, res);
return
Should do something like that:
try
responseData = self._callEndpoint endpointContext, endpoint
catch error
return {
statusCode: error.error
body: {status: 'error', message: error.reason}
}
or maybe that ironRouterSendErrorToResponse should be flagged to turn it off/on.
What you think?
I have the same doubt... it would help a lot to throw Meteor.Error
Please take a look @kahmali =)