javascript - 使用 Future 通过异步调用正确处理 Meteor 错误

标签 javascript asynchronous meteor node-fibers

我想知道在使用异步方法时如何正确处理 Meteor 的错误。我尝试了以下操作,但在客户端回调的结果参数中返回了错误,而不是错误参数。

服务器代码:

Future = Npm.require('fibers/future');

Meteor.methods({
    'myServerMethod': function(){
        var future = new Future();

        // URL to some remote API
        var url = UrlOfTheApiIWantToCall;

        HTTP.get(url, {//other params as a hash},
            function (error, result) {
                if (!error) {
                    future.return(result);
                } else {
                    future.return(error);
                }
            }
        );

        return future.wait();
    }
});

客户端代码:

Meteor.call('myServerMethod', function (error, result) {
    if(error){
        console.warn(error);
    }

    console.log('result', result);
});

正如我上面所说,当服务器端的 HTTP.get() 返回错误时,“错误”在客户端事件中始终未定义。我还尝试在服务器端将 future.return(error); 替换为 future.throw(error); ,但这确实会在服务器端引发错误。客户端错误参数然后得到 500 服务器错误,尽管在服务器上抛出的错误是 401 未经授权的错误。

那么,能否正确使用Fiber的Future,让客户端回调接收到与服务端回调相同的错误参数?

最佳答案

根据 http://docs.meteor.com/#/full/meteor_error 处的 Meteor.Error 文档

Methods can throw any kind of exception. But Meteor.Error is the only kind of error that a server will send to the client. If a method function throws a different exception, then it will be mapped to a sanitized version on the wire. Specifically, if the sanitizedError field on the thrown error is set to a Meteor.Error, then that error will be sent to the client. Otherwise, if no sanitized version is available, the client gets Meteor.Error(500, 'Internal server error').

这就是您在客户端收到 500 服务器错误 的原因。如果您想保留错误消息并将其发送给客户端,您可以这样做:

Future = Npm.require('fibers/future');

Meteor.methods({
    'myServerMethod': function(){
        var future = new Future();

        // URL to some remote API
        var url = UrlOfTheApiIWantToCall;

        HTTP.get(url, {//other params as a hash},
            function (error, result) {
                if (!error) {
                    future.return(result);
                } else {
                    future.throw(error);
                }
            }
        );

        try {
            return future.wait();
        }
        catch(err) {
            // Replace this with whatever you want sent to the client.
            throw new Meteor.Error("http-error", err);
        }
    }
});

关于javascript - 使用 Future 通过异步调用正确处理 Meteor 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32016729/

相关文章:

javascript - JS 获取宽度不按预期工作

javascript - 在 JQuery 中插入 PHP

node.js - Meteor.js 和 Apache/Nginx 在同一台服务器上,服务不同的域名

javascript - 使用 javascript 添加/创建输入

javascript - 如何在异步操作中指示 "doneness"

c# - 同步延续到底什么时候是危险的?

javascript - 如何 "cancel/abort"已经触发的异步任务的副作用?

meteor - Meteor 是否支持嵌套的助手(子表达式)?

meteor - 从服务器获取值

javascript - 如何实现重复的 Promise 调用链?