首页 > 解决方案 > 在我正在构建的包中,如何将由 promise 创建的错误的处理留给包的消费者?

问题描述

这是我正在构建的一个简单包。

var fetch = require('node-fetch');

function createClient(host, port, body) {
    function httpRequestHelper(body, extractResponseCallback) {
        return fetch(`${host}:${port}`, {
            method: 'post',
            body: JSON.stringify(body)
        })
        .then(function (response) {
            if (!response.ok) {
                throw Error(response.statusText);
            }
            return response.json();
        })
        .then(function(response) {
            if (response.type === 'error') {
                throw Error(response);
            }
            return extractResponseCallback(response);
        })
        .catch(function(error) {
            return Promise.reject(error);
        });    
    }

    function recordings() {
        return httpRequestHelper({ type: 'request', cmd: 'recordings' });
    }

    return {
        recordings: recordings,
    };
}

exports.createClient = createClient;

我希望这个包的使用者能够按照 htey 认为合适的方式处理错误,例如:

try {
    let recordingsResponse = await client.recordings()
    console.log(recordingsResponse);    
} catch (error) {
    console.log(error);
}

但是,使用我当前的代码,我得到了错误:

(node:81180) UnhandledPromiseRejectionWarning: TypeError: undefined is not a function
    at checkCreateProject (/Users/xp025106/Dev/qip-js-http-client/examples.js:15:17)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:81180) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:81180) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
seldmac25073:qip-js-http-client xp025106$

我怎样才能解决这个问题?

PS。在此之前我没有写太多代码供其他人使用,因此欢迎任何代码改进建议

标签: javascriptnode.jspromise

解决方案


如果您希望消费者自己处理错误状态,最简单的解决方案就是不捕获任何错误。但是,您应该处理可能暴露敏感信息的错误或由复杂操作引起的错误;在这些情况下,使用描述性较少的错误消息而不是完整的堆栈跟踪或更具体的错误消息来捕获和重新抛出(或拒绝)可能是一个更好的主意。

看起来您的httpRequestHelper函数需要两个参数:bodyextractResponseCallback。您导出recording的函数只使用一个参数调用它 - 因此错误是关于undefined不是函数。

解决方案是导出闭包、绑定函数或委托 Function 参数以传入httpRequestHelper期望的第二个参数。在您的情况下,委托参数可能是您想要的,因为您的消费者仍然需要再次调用闭包和绑定函数。

关闭

function recordings() {
  return function(callback) {
    return httpRequestHelper({ type: 'request', cmd: 'recordings' }, callback);
  };
}

绑定函数

function recordings() {
  return httpRequestHelper.bind(null, { type: 'request', cmd: 'recordings' });
}

委托论证

function recordings(callback) {
  return httpRequestHelper({ type: 'request', cmd: 'recordings' }, callback);
}

推荐阅读