[solved] Callback error handling of mongo insert within a method


I’m trying to insert something into a mongo collection within a Meteor.method and use a callback to handle errors.

I thought I could just throw an error inside the error callback but evidently you can’t do this. Throwing an error here simply prints the error to the server console and continues on as normal. Nothing is sent back to the client calling the method.

What I want to do is tell the client there’s an error and stop.

Is there any way to do this? I don’t really want to use a try/catch block and use a blocking mongo insert and catch the exception instead of using a callback but that’s all I can think of, there must be a non-hacky way of doing something this simple?

Relevant code below:

    'uploadWalletImage': function (fileName, imageOf, binaryData, md5) {
        WalletImages.insert({_id: md5, 'imageOf': imageOf}, function(error,result){
if(error){throw new Meteor.Error('error', 'reason for error')}; //reported on server console only
//other stuff here proceeds as normal even when an error has been thrown

Meteor.call('uploadWalletImage', file.name, event.target.id, reader.result, md5, function(error, result){
       console.log(error.reason); //nothing reported


The way to send exceptions back to the client is with throw new Meteor.Error():

EDIT: Oops - I see you’re already using it! However, your “other stuff” line is executed asynchronously, so the result isn’t available there. You could use “sync-style” with try/catch:

  uploadWalletImage(fileName, imageOf, binaryData, md5) {
    try {
      const result = WalletImages.insert({ _id: md5, 'imageOf': imageOf });
      // do other stuff here
    } catch(error) {
      throw new Meteor.Error('error', 'reason for error');


That’s exactly what I’m doing here, but it doesn’t work.

edit: I replied and you edited at the same time :slight_smile:


Yeah - just noticed and edited my reply!


That’s what I’ve actually started doing since I posted this, and it works of course, I was just hoping to find a cleaner way. Maybe I’m being pedantic.

I see the asynchronous thing now (facepalm) but do you know of any reason why Meteor.Error does not propagate to the client in the code in my original post?


Same asynchronous reason - it’s too late - the method has completed by then (presumably with undefined).


Ah yes, I see now. Not sure why that didn’t make sense to me before.