Share via


Web API Helper 程式碼:CrmHttpResponseException 類別

 

發行︰ 2017年1月

適用於: Dynamics 365 (online)、Dynamics 365 (on-premises)、Dynamics CRM 2016、Dynamics CRM Online

使用 CrmHttpResponseException 類別代表 Dynamics 365 Web API 呼叫期間產生的 HTTP 狀態錯誤。 此類別衍生自標準 .NET System.Exception 類別,可輕鬆與您現有的例外狀況處理機制整合。 如需一般資訊,請參閱處理和擲回例外狀況

CrmHttpResponseException 類別位於 Exceptions.cs 檔案中,在 CRM SDK Web API Helper 程式庫中。 它在其他 Helper 程式庫類別和 C# Web API 範例中大量使用。 如需詳細資訊,請參閱使用 Microsoft Dynamics 365 Web API Helper 程式庫 (C#)

此類別利用 JSON 字串處理功能,從開放原始碼 Json.NET 程式庫。

類別成員

下表顯示 CrmHttpResponseException 類別的公用成員。

Dynamics 365 Web API Helper 程式庫-CrmHttpResponseException 類別圖表

CrmHttpResponseException 類別

屬性:

StackTrace – 立即框架的字串表示,在 Dynamics 365 伺服器呼叫堆疊上,當例外狀況擲回時 (如有的話)。


方法

建構函式會初始化此類別的執行個體,且需要 HttpContent 參數和選用的內部例外狀況參數。

ExtractMessageFromContent – 此靜態方法會從指定的 HTTP 內容參數擷取錯誤訊息。

使用方式

一般而言,您會在處理隨 HTTP 回覆訊息傳回的狀態錯誤時,建立和擲回 CrmHttpResponseException 物件。 例如,下列程式碼會在 WhoAmI Function 函數呼叫失敗時擲回這類錯誤。

response = await httpClient.GetAsync("WhoAmI", HttpCompletionOption.ResponseContentRead);
if (!response.IsSuccessStatusCode)
{ 
    throw new CrmHttpResponseException(response.Content); 
}

您可以攔截和處理擲回的 CrmHttpResponseException 物件,類似其他標準 .NET 例外狀況。

重要

如果您使用 HttpResponseMessage.EnsureSuccessStatusCode 方法自動將 HTTP 回覆錯誤轉換成擲回的 HttpRequestException 物件,則此方法會防止使用 CrmHttpResponseException 類別。 請注意,如果您使用此方法,則在例外狀況處理期間,有許多回覆訊息詳細資料將無法使用,包括狀態碼。

類別清單

此類別的最新來源位於 CRM SDK Web API Helper 程式庫 NuGet 套件中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Microsoft.Crm.Sdk.Samples.HelperCode
{
    /// <summary>
    /// Produces a populated exception from an error message in the content of an HTTP response. 
    /// </summary>
    public class CrmHttpResponseException : System.Exception
    {
        #region Properties
        private static string _stackTrace;

        /// <summary>
        /// Gets a string representation of the immediate frames on the call stack.
        /// </summary>
        public override string StackTrace
        {
            get { return _stackTrace; }
        }
        #endregion Properties

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the CrmHttpResponseException class.
        /// </summary>
        /// <param name="content">The populated HTTP content in Json format.</param>
        public CrmHttpResponseException(HttpContent content)
            : base(ExtractMessageFromContent(content)) { }

        /// <summary>
        /// Initializes a new instance of the CrmHttpResponseException class.
        /// </summary>
        /// <param name="content">The populated HTTP content in Json format.</param>
        /// <param name="innerexception">The exception that is the cause of the current exception, or a null reference
        /// if no inner exception is specified.</param>
        public CrmHttpResponseException(HttpContent content, Exception innerexception)
            : base(ExtractMessageFromContent(content), innerexception) { }

        #endregion Constructors

        #region Methods
        /// <summary>
        /// Extracts the CRM specific error message and stack trace from an HTTP content. 
        /// </summary>
        /// <param name="content">The HTTP content in Json format.</param>
        /// <returns>The error message.</returns>
        private static string ExtractMessageFromContent(HttpContent content)
        {
            string message = String.Empty;
            string downloadedContent = content.ReadAsStringAsync().Result;
            if (content.Headers.ContentType.MediaType.Equals("text/plain"))
            {
                message = downloadedContent;
            }
            else if (content.Headers.ContentType.MediaType.Equals("application/json"))
            {
                JObject jcontent = (JObject)JsonConvert.DeserializeObject(downloadedContent);
                IDictionary<string, JToken> d = jcontent;

                // An error message is returned in the content under the 'error' key. 
                if (d.ContainsKey("error"))
                {
                    JObject error = (JObject)jcontent.Property("error").Value;
                    message = (String)error.Property("message").Value;
                }
                else if (d.ContainsKey("Message"))
                    message = (String)jcontent.Property("Message").Value;

                if (d.ContainsKey("StackTrace"))
                    _stackTrace = (String)jcontent.Property("StackTrace").Value;
            }
            else if (content.Headers.ContentType.MediaType.Equals("text/html"))
            {
                message = "HTML content that was returned is shown below.";
                message += "\n\n" + downloadedContent;
            }
            else
            {
                message = String.Format("No handler is available for content in the {0} format.",  
                    content.Headers.ContentType.MediaType.ToString());
            }
            return message;
            #endregion Methods
        }
    }
}

另請參閱

開始使用 Microsoft Dynamics 365 Web API (C#)
在 Visual Studio (C#) 中啟動 Dynamics 365 Web API 專案
使用 Microsoft Dynamics 365 Web API Helper 程式庫 (C#)
Web API Helper 程式碼:驗證類別
Web API Helper 程式碼︰組態類別

Microsoft Dynamics 365

© 2017 Microsoft. 著作權所有,並保留一切權利。 著作權