웹 API 도우미 코드: CrmHttpResponseException 클래스

 

게시 날짜: 2017년 1월

적용 대상: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

CrmHttpResponseException 클래스를 사용하여 Dynamics 365 웹 API를 호출하는 동안 발생한 HTTP 상태 오류를 나타냅니다. 이 클래스는 표준 .NET System.Exception 클래스에서 파생되므로 기존 예외 처리 메커니즘과 쉽게 통합할 수 있습니다. 자세한 내용은 예외 처리 및 throw를 참고하십시오.

CrmHttpResponseException 클래스는 CRM SDK 웹 API 도우미 라이브러리의 Exceptions.cs 파일에 있습니다. 다른 도우미 라이브러리 클래스 및 C# 웹 API 샘플에서 광범위하게 사용됩니다. 자세한 내용은 Microsoft Dynamics 365 웹 API 도우미 라이브러리(C#) 사용을 참조하십시오.

이 클래스는 오픈 소스 Json.NET 라이브러리에서 JSON 문자열 처리 기능을 사용합니다.

클래스 구성원

다음 표에서 CrmHttpResponseException 클래스의 공통 구성원을 보여줍니다.

Dynamics 365 웹 API 도우미 라이브러리-CrmHttpResponseException 클래스 다이어그램

CrmHttpResponseException 클래스

속성:

StackTrace - 문자열은 가능한 경우 예외가 throw되었을 때 Dynamics 365 서버의 호출 스택에 즉각적인 프레임을 나타냅니다.


메서드:

생성자는 이 클래스의 인스턴스를 초기화하고 HttpContent 매개 변수 및 선택 사항인 내부 예외 매개 변수를 요구합니다.

ExtractMessageFromContent - 이 정적 메서드는 지정된 HTTP 콘텐츠 매개 변수에서 오류 메시지를 추출합니다.

사용법

일반적으로 상태 오류를 처리할 때 HTTP 응답 메시지가 반환될 때 CrmHttpResponseException 개체를 만들고 throw합니다. 예를 들어, 다음 코드는 WhoAmI Function 함수 호출이 실패하는 경우 이러한 오류를 throw합니다.

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

throw된 CrmHttpResponseException 개체를 다른 표준 .NET 예외와 유사하게 찾아내고 처리할 수 있습니다.

중요

HttpResponseMessage.EnsureSuccessStatusCode 메서드 사용하여 자동으로 HTTP 응답 오류를 throw된 HttpRequestException 개체에 변환하는 경우, 이 방법은 CrmHttpResponseException 클래스 사용을 배제합니다. 참고로 이 방법을 사용하면 예외를 처리하는 동안 상태 코드를 포함한 많은 응답 메시지 세부 정보는 확인할 수 없습니다.

클래스 목록

이 클래스에 대한 최신 정보는 CRM SDK 웹 API 도우미 라이브러리 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 웹 API(C#) 시작
Visual Studio(C#)에서 Dynamics 365 웹 API 프로젝트 시작
Microsoft Dynamics 365 웹 API 도우미 라이브러리(C#) 사용
웹 API 도우미 코드: 인증 클래스
웹 API 도우미 코드: 구성 클래스

Microsoft Dynamics 365

© 2017 Microsoft. All rights reserved. 저작권 정보