如何在Rx OnNext处理程序中抛出错误
问题描述:
如果存在某种情况,我想在我的OnNext处理程序中生成错误,类似于:
I want to generate an error in my OnNext handler if a certain condition exists, similar to this:
private void multipleLongRunningProcessBtn_Click(object sender, EventArgs e)
{
//create a cold stream of values to process
var lst = new List<string>();
lst.Add("http://www.reddit.com/");
lst.Add("http://www.yahoo.com/");
lst.Add("http://www.hello-online.org/");
lst.ToObservable().ObserveOn(listBox1).Subscribe(
url => ProcessUrl(url),
err => PostMessage("OnError"),
() => PostMessage("Complete"));
}
public void ProcessUrl(string pUrl)
{
if (pUrl.Contains("hello-online")) throw new Exception("Bad URL");
Thread.Sleep(3000); //do lengthy work here
}
How do I properly generate the error? The exception is causing the app to crash.
答
嗨布拉德,
您需要做类似的事情;
You would need to do something like this;
public void ProcessUrl(string pUrl)
{
try
{
if (pUrl.Contains("hello-online"))
throw new Exception("Bad URL");
Thread.Sleep(3000); //do lengthy work here
}
catch(Exception ex)
{
ProcessError(ex);
}
}