Throw async error back to client

Hi!

I have a client fn that calls a Server Helper method which then makes a call to another Server Helper to download data from an API.

So it’s like Client->ServerMd1->ServerMd2.

Client Code

Meteor.call('ServerMd1', (err, res) => {
   if (err) return Bert.alert("err","danger","warning-top");
});

Server Code

Meteor.methods({
  'serverMd1'(foo) {
   try {
        await Meteor.call('serverMd2', foo);
   } catch(error) {
      throw error;
  }
  },
  'serverMd2': async function (foo) {
       throw new Meteor Error("API Error", "Something happened while making req");  
  });
  },

So the error thrown in serverMd2 isn’t trickling up to the client. However, an error thrown by serverMd1 would. What’s the desired way to do this?

You can’t await a Meteor call, since it will never return a Promise.

See Meteor#call (documentation)
If you do not pass a callback on the server, the method invocation will block until the method is complete. It will eventually return the return value of the method, or it will throw an exception if the method threw an exception. (Possibly mapped to 500 Server Error if the exception happened remotely and it was not a Meteor.Error exception.)

  • Remove try-catch and await from method 1.
  • ideally don’t call a method from a method. It is possible to do that, but it doesn’t make much sense, it weighs down on the server and slows down execution. If you have to invoke the functionality of another method, pull it into a simple function accessible to both methods and call that function in each.
  • of course if the common functionality is now in an async function, method1’s function will need to be async, provided that you need to await its execution. If await is not necessary, you can simply return the result of the function invocation, which is going to be a Promise. Meteor will recognize it and will wait for a resolve or reject.
1 Like

The Meteor.call structure is Meteor.call(‘method’, {…arguments…}, callback). You are missing the arguments, if no arguments, just use an empty object. https://guide.meteor.com/methods.html

1 Like