问题描述
我创建了一个简单的rx运算符,该运算符将字符串流转换为jsons流,并且工作正常.但是,我希望能够引发一个自定义异常,并且我不确定如何调用订阅的on_error
方法
I've created a simple rx operator that converts a stream of strings to a stream of jsons and it works fine. However, I would like to be able to raise a custom exception and I am not sure how to call the on_error
method of the subscription
运算符称为convertStringToJson
,可以在这里找到工作示例: https://github.com/cipriancaba/rxcpp-examples/blob/master/src/SimpleOperators.cpp
The operator is called convertStringToJson
and a working sample can be found here: https://github.com/cipriancaba/rxcpp-examples/blob/master/src/SimpleOperators.cpp
function<observable<json>(observable<string>)> SimpleOperators::convertFromStringToJson() {
return [](observable<string> $str) {
return $str |
Rx::map([](const string s) {
return json::parse(s);
});
};
}
推荐答案
如果使用try/catch转换异常,则rxcpp将起作用.
rxcpp will work if you use try/catch to translate the exception.
但是,预期的模式是使用on_error_resume_next()转换异常.
However, the intended pattern is to use on_error_resume_next() to translate the exception.
这是代码:
function<observable<json>(observable<string>)> SimpleOperators::convertFromStringToJson() {
return [](observable<string> $str) {
return $str |
Rx::map([](const string& s) {
return json::parse(s);
}) |
Rx::on_error_resume_next([](std::exception_ptr){
return Rx::error<json>(runtime_error("custom exception"));
});
};
}
我用这段代码在github上打开了一个拉取请求.
I opened a pull request on github with this code.
https://github.com/cipriancaba/rxcpp-examples/pull/1
这篇关于如何在自定义rxcpp运算符上调用on_error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!