如何从 Meteor.js 中方法内的方法返回错误

How to return an error from a method inside a method in Meteor.js

本文关键字:方法 返回 错误 Meteor js      更新时间:2023-09-26

>我在 Meteor.js 中的另一个方法中运行一个方法,我想将错误返回给客户端,但我在控制台上收到此错误:

Exception in delivering result of invoking 'validarCupon':

这是我实际在客户端上调用的方法:

Meteor.methods({
  hacerPedido:function(){
    var carrito = CarritoUsuario.findOne({idUsuario: Meteor.userId()});
    var cupon = carrito.cupon;
    //Texto y lógica del cupón
    Meteor.call("validarCupon", cupon.codigo, function(error, result){
      if(error){
        throw new Meteor.Error("cupon-invalido", error.reason);
      }
    });
    return creditoUsuario;
  }
});

我想做的是从名为"validarCupon"的方法获取错误,并将其传递给调用方法"hacerPedido"的客户端。

您正在异步调用内部方法,这会阻止您将任何内容抛出回调用方,因为return creditoUsario很可能在抛出之前被调用。

但希望您不需要异步执行此操作,在这种情况下,您只需执行以下操作:

Meteor.methods({
  hacerPedido:function(){
    var carrito = CarritoUsuario.findOne({idUsuario: Meteor.userId()});
    var cupon = carrito.cupon;
    //Texto y lógica del cupón
    Meteor.call("validarCupon", cupon.codigo);
    return creditoUsuario;
  }
});

因为例外会冒出来。因此,validarCon 方法中的任何异常都会自动抛出给客户端。

如果您确实需要该方法异步运行,则需要稍微更改逻辑,因为一旦return发生(方法主体结束),就没有更多的基础可以与客户端进行通信。

另外,如果您使用上面的解决方案,我建议甚至不要在服务器中使用方法调用,而是使其成为简单的函数。

Meteor.call 的 meteor 文档中,它说在服务器端,你不需要回调,meteor 调用将是同步的。

在服务器上

在服务器上,您不必传递回调 — 方法调用将简单地>块,直到方法完成,返回结果或抛出>异常,就像您直接调用函数一样:

服务器上的同步调用,无回调 var result = Meteor.call('commentOnPost', comment, postId);

所以,我认为你应该做这样的事情,

Meteor.methods({
  hacerPedido:function(){
    var carrito = CarritoUsuario.findOne({idUsuario: Meteor.userId()});
    var cupon = carrito.cupon;
    //Texto y lógica del cupón
    try {
        var result = Meteor.call("validarCupon", cupon.codigo);
    } catch (error) {
        throw new Meteor.Error("cupon-invalido", error.reason);
    }
    return creditoUsuario;
  }
});