![](/img/trans.png)
[英]monotouch webexception can't be caught within try/catch when data is reading from received response stream
[英]WebException not caught in try/catch
我看到了几个有类似问题的帖子,但是没有解决方案:/
我通过使用控制台应用程序调试Windows服务。 它在网站上执行任务,并且必须能够收集HTTP代码状态以创建日志。 如您所见,敏感代码在try / catch中。
当我调试(F5)时,我没有捕获到WebException。 当我运行(CTRL + F5)时,异常消息将写在控制台中并停止我的程序。 这是我的代码:
public partial class Schedulor : ServiceBase
{
void RunTasks()
{
schedulor.Start();
List<Task> task = new List<Task>();
foreach (TaskPlanner tp in listTp)
{
if (tp.CountDown == 0 && tp.IsRunning == false)
{
// Initialisation lors de GetTasks()
tp.IsRunning = true;
try
{
task.Add(Task.Factory.StartNew(() => tr = tp.ExecuteBot.Execute())); // WEBEXECPTION HERE (cannot find 404)
}
catch (Exception e)
{
if (e is WebException)
{
// treatment
}
}
}
}
Task.WaitAll(task.ToArray());
CreateLogs();
}
}
public class Bot : IBot
{
public TaskResult Execute()
{
TaskResult tr = new TaskResult();
int codeResponse, timeout;
string credentials;
try
{
WebRequest wrSettings = WebRequest.Create(settings.Url);
// treatment
}
catch (Exception e)
{
//Console.WriteLine(e.Message);
if (e is WebException)
{
var code = ((HttpWebResponse)((WebException)e).Response).StatusCode;
if ((int)code != settings.HttpResponse)
{
tr.MyResult = TaskResult.Result.nok;
goto next;
}
else tr.MyResult = TaskResult.Result.ok;
}
}
next:
return tr;
}
}
我不明白为什么我的钓钩不起作用。 我需要处理此信息,因为该任务可以测试网站是否返回404或其他任何内容。
提前致谢
编辑:-----------
我按要求减少代码,因为删除的代码不是真正的问题
您应该在task中捕获该异常。 添加另一种方法,并创建类似于以下内容的任务:
task.Add(Task.Factory.StartNew(() => Process(tp)));
void Process(TaskPlanner tp)
{
try
{
tp.ExecuteBot.Execute();
}
catch (WebException wex)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.