我正在尝试执行此函数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()末尾的捕获,我将得到“未捕获(承诺)”。
答案 0 :(得分:0)
是的,您应该删除catch
中的varlinkCallChannel
。
您的问题出在varlinkCall
:
export function varlinkCall(channelOptions, method, parameters) {
var channel = cockpit.channel(Object.assign({payload: "stream", binary: true, superuser: "require" }, channelOptions));
var promise1 = varlinkCallChannel(channel, method, parameters);
var promise2 = promise1.finally(() => channel.close());
// ^^^^^^^^^^^^^^^
return promise1;
}
在这里,您正在创建第二个承诺,该承诺将像您返回的promise1
一样被拒绝,而对promise2
的拒绝在任何地方都不会得到处理。您将要返回链式承诺:
export function varlinkCall(channelOptions, method, parameters) {
var channel = cockpit.channel(Object.assign({payload: "stream", binary: true, superuser: "require" }, channelOptions));
return varlinkCallChannel(channel, method, parameters).finally(() => {
channel.close()
});
}