【问题标题】:How to extract "Message" part from Google API error message如何从 Google API 错误消息中提取“消息”部分
【发布时间】:2014-12-31 05:30:24
【问题描述】:

我需要格式化从 Google 返回的异常消息,并以一种很好的方式呈现给最终用户。 (使用 C#)

异常的格式:(本例中我调用的是Admin SDK。)

Google.Apis.Requests.RequestError.Entity 已存在。 [409]。 错误 [。 消息[实体已存在。] 地点 [ - ] 原因[重复] 域 [全局] .]

另一个错误,

已达到 Google.Apis.Requests.RequestError.Domain 用户限制。 [412]。 错误 [。 消息[已达到域用户限制。] 位置 [If-Match - 标题] 原因[limitExceeded] 域[全局] .]

如何从上述错误消息中提取“消息”? (“实体已存在。”或“已达到域用户限制。”在上面的示例中)

【问题讨论】:

    标签: c# google-api


    【解决方案1】:

    这是 Regix 的工作。以下应该可以满足您的需要:

            string message1 = "Google.Apis.Requests.RequestError.Entity already exists. "
                              +"[409]. Errors [. Message[Entity already exists.] Location [ - ] Reason [duplicate] Domain [global] .]";
            string message2 = "Google.Apis.Requests.RequestError.Domain user limit reached. "
                              +"[412]. Errors [. Message[Domain user limit reached.] Location [If-Match - header] Reason[limitExceeded] Domain[global] .]";
    
            string pattern = @"Message\[((\w+\s){2,}(\w+\s?)*)\.\]";
    
            Regex regex = new Regex(pattern);
    
            Match m = regex.Match(message1); //or regex.Match(message2)
            if (m.Success)
            {
                Group g = m.Groups[1]; //m.Groups[0] will Match 'Message[.....]'
                CaptureCollection cc = g.Captures;
    
                for (int i = 0; i < cc.Count; i++)
                {
                    Capture c = cc[i];
                    Console.WriteLine("Message: {0}", c);
                }
            }
    
            Console.ReadLine();
    

    【讨论】:

    • 遇到了一个小问题,“Google.Apis.Requests.RequestError.Not Authorized to access this resource/api [403].Errors [.Message[Not Authorized to access this resource/api]位置[-] 原因[禁止] 域[全局].].";.此错误返回空,因为此处的“消息”(未授权访问此资源/api)没有句号“。”。有什么建议吗?
    【解决方案2】:

    试试这个模式。

    字符串模式 = @"Message[([A-Za-z0-9-\s*]+)]*";

    【讨论】:

    • 这解决了没有“。”的消息的问题。在消息块中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2023-04-03
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多