WPF,处理错误和警告消息

时间:2010-11-13 19:14:24

标签: c# wpf

我需要提前。我发送HTTP GET请求并解析HTML响应,如果HTML响应(html字符串)包含一些子字符串,我想发送到客户端应用程序,(WPF应用程序)一些错误/警告消息。

在我的解决方案中,如果html字符串包含一些子字符串,我会抛出新的异常,这是愚蠢的,什么解决方案适合这个问题?

代码在这里:

    private bool SendRp(string postData)
    {
        bool result = false;

        const string parameters = @"&lok=1&rpI=3";
        string htmlStringResult = HttpPostReq(
            new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PokecUrl.Rp, Account.SessionId, parameters)), postData);
        try
        {
            if (htmlStringResult.ToLower(new CultureInfo("sk-Sk")).Contains("is is empty"))
            {
                throw new ArgumentException("ID is empty!");
            }
            if (htmlStringResult.ToLower(new CultureInfo("sk-Sk")).Contains("id does not exist"))
            {
                throw new ArgumentException("ID does not exist.");
            }
            if (htmlStringResult.ToLower(new CultureInfo("sk-Sk")).Contains("blocked"))
            {
                throw new WebException("Your ID is blocked!");
            }
            if (!htmlStringResult.ToLower(new CultureInfo("sk-Sk")).Contains("message was send"))
            {
                Match match = Regex.Match(htmlStringResult, @"\bhs=\w{15}\b");

                if (match.Success)
                {
                    result = true;
                }
                else
                {
                    throw new Exception("Some problem");  
                }

            }
            return result;
        }
        catch (Exception exception)
        {
            throw exception;
        }
    }

1 个答案:

答案 0 :(得分:0)

如果由于解析HTML而要存储多个错误/警告,请使用一组消息。

您可以像这样定义这样的消息集合:

public class MessageCollection : Collection<Message>
{
}

public class Message
{
    public Message(Severity severity, string message)
    {
        Severity = severity;
        Message = message;
    }

    public Severity Severity { get; private set; }
    public string Message { get; private set; }
}

public enum Severity
{
    Error,
    Warning,
    Info
}

您可以像这样使用这些类:

var messages = new MessageCollection();

messages.Add(new Message(Severity.Warning, "This is a warning"));
messages.Add(new Message(Severity.Error, "This is an error"));

通过这种方式,您可以从解析HTML中收集多条消息。如果您愿意,您仍然可以抛出异常,但随后会发出以下消息:

public class MessageException : Exception
{
    public MessageException(MessageCollection messages)
        : base("One or more messages were collected")
    {
        Messages = messages;
    }

    public MessageCollection Messages { get; private set; }
}

然后像这样抛出这个异常:

var messages = new MessageCollection();

messages.Add(new Message(Severity.Warning, "This is a warning"));
messages.Add(new Message(Severity.Error, "This is an error"));

if (messages.Count > 0)
    throw new MessageException(messages);