Server Validated Method doesn't display validation error on client

Hi! I have this server side validated method imports/api/Shops/server/methods.js:

export const shopGeocodeAddress = new ValidatedMethod({
  name: 'shops.geocodeAddress',
  validate: new SimpleSchema({
    streetName: { type: String },
    houseNumber: { type: Number },
    city: { type: String },
    state: { type: String },
    country: { type: String },
    zip: { type: String, optional: true },
  }).validator(),
  run({ streetName, houseNumber, city, state, country, zip }) {
...
...
...
...
    return location;
  },
});

To test validation error message on the client, I’m sending houseNumber as string which will get the method to fail, as it expects houseNumber as Number. So far so good. I’m getting a validation error on the server console like this:

I20190418-10:55:28.605(-3)? Exception while invoking method ‘shops.geocodeAddress’ { ClientError: House number must be of type Number


I20190418-10:55:28.608(-3)? errorType: ‘ClientError’,
I20190418-10:55:28.608(-3)? name: ‘ClientError’,
I20190418-10:55:28.608(-3)? error: ‘validation-error’,
I20190418-10:55:28.609(-3)? details:
I20190418-10:55:28.609(-3)? [ { name: ‘houseNumber’,
I20190418-10:55:28.609(-3)? value: NaN,
I20190418-10:55:28.609(-3)? type: ‘expectedType’,
I20190418-10:55:28.609(-3)? dataType: ‘Number’,
I20190418-10:55:28.609(-3)? message: ‘House number debe ser del tipo Number’ } ] }

But on the client I get only an internal server error like this:

details: undefined
error: 500
errorType: “Meteor.Error”
isClientSafe: true
message: “Internal server error [500]”
reason: “Internal server error”

Thus I can’t indicate the client which type of error is, or which field must be changed in order for the method to be run correctly.

Is there a way to catch validation error on server methods and send them to the client?

Thanks in advise!

I can’t remember how I fixed this but I have some suggestions.

Try adding ValidationError with the mdg package: meteor add mdg:validation-error

If that doesn’t work, there’s this bit of instruction from the docs of simple-schema: https://github.com/aldeed/simple-schema-js#customize-the-error-that-is-thrown

For example, in a Meteor app, in order to ensure that the error details are sent back to the client when throwing an error in a server method, you can convert it to a Meteor.Error:

import SimpleSchema from 'simpl-schema';

SimpleSchema.defineValidationErrorTransform(error => {
  const ddpError = new Meteor.Error(error.message);
  ddpError.error = 'validation-error';
  ddpError.details = error.details;
  return ddpError;
});
2 Likes

I answered to you in Stackoverflow. Is your method in the common space accessible from both client and server?

Great! Thanks! that did the trick! Just added a server file and added to the startup script defining the SimpleSchema error transform and voila!

Thanks a lot!

1 Like

Thanks! I used @coagmano answer and it worked!