【发布时间】:2019-01-08 04:49:05
【问题描述】:
我正在尝试执行这个函数 varlinkCall 并在 .then() 中添加一个回调函数,并在 .catch() 中使用 varlinkCall 处理 err。
varlinkCall(utils.PODMAN, "io.projectatomic.podman.RemoveImage", JSON.parse('{"name":"' + image.Id + '"}'))
.then((reply) => {
console.log(reply.image);
})
.catch(ex => {
console.log(ex);
})
varlinkCall() 调用了 varlinkCallChannel(),我在 varlinkCallChannel() 的末尾添加了 .catch(),但是我在 varlinkCall() 函数中无法得到错误消息,它是由 varlinkCallChannel() 咳出来的。我怎样才能得到错误信息?
function varlinkCallChannel(channel, method, parameters) {
return new Promise((resolve, reject) => {
function on_close(event, options) {
reject(options.problem || options);
}
function on_message(event, data) {
channel.removeEventListener("message", on_message);
channel.removeEventListener("close", on_close);
// FIXME: support answer in multiple chunks until null byte
if (data[data.length - 1] != 0) {
reject("protocol error: expecting terminating 0");
return;
}
var reply = decoder.decode(data.slice(0, -1));
var json = JSON.parse(reply);
if (json.error)
reject(json.error)
else if (json.parameters) {
// debugging
// console.log("varlinkCall", method, "→", JSON.stringify(json.parameters));
resolve(json.parameters)
} else
reject("protocol error: reply has neither parameters nor error: " + reply);
}
channel.addEventListener("close", on_close);
channel.addEventListener("message", on_message);
channel.send(encoder.encode(JSON.stringify({ method, parameters: (parameters || {}) })));
channel.send([0]); // message separator
})
.catch(err=>{console.log(err)});
}
/**
* Do a varlink call on a new channel. This is more expensive than
* `varlinkCallChannel()` but allows multiple parallel calls.
*/
export function varlinkCall(channelOptions, method, parameters) {
var channel = cockpit.channel(Object.assign({payload: "stream", binary: true, superuser: "require" }, channelOptions));
var response = varlinkCallChannel(channel, method, parameters);
response.finally(() => channel.close());
return response;
}
如果我删除 varlinkCallChannel() 末尾的 catch,我将得到“Uncaught (in promise)”。
【问题讨论】:
-
为了记录而捕捉到的地方,记得重新抛出错误。此外,请始终使用
Error(或TypeError、RangeError等)拒绝。 -
thx,你能给出一个具体的实现吗,rethrow?
标签: javascript reactjs promise