C++용 Azure SDK의 오류 처리는 주로 C++ 예외를 통해 구현됩니다. 이 방법은 표준 C++ 사례에 부합하며 SDK 전체에서 명확한 오류 보고 및 처리를 허용합니다. C++ 애플리케이션이 Azure 서비스와 상호 작용하는 경우 인증 문제, 서비스 사용 불가, 잘못된 요청 또는 리소스 제약 조건과 같은 다양한 이유로 작업이 실패할 수 있습니다. SDK는 이러한 오류를 오류에 대한 자세한 정보를 제공하는 예외로 캡처합니다.
예외 계층 구조
핵심 예외 유형
C++용 Azure SDK는 예외 클래스의 계층 구조를 사용하며 가장 중요한 클래스는 다음과 같습니다.
std::runtime_error- Azure 관련 예외가 상속하는 기본 C++ 표준 예외입니다.Azure::Core::RequestFailedException- 파생된std::runtime_error것으로, 모든 Azure 서비스 요청 실패에 대한 기본 예외입니다.azure/core/exception.hpp에 정의된 이 예외는 Azure 서비스 요청이 실패할 때 발생합니다. 이 콘솔은 다음과 같은 기능을 제공합니다.- HTTP 상태 코드
- 서비스의 오류 코드
- 오류 메시지
- 문제 해결을 위한 ID 요청
- 원시 HTTP 응답
Azure::Core::OperationCancelledException-std::runtime_error에서 파생된 이 예외는 일반적으로 컨텍스트 개체를 통해 작업이 취소될 때 발생합니다.Azure::Core::Http::TransportException-Azure::Core::RequestFailedException에서 파생된 이 예외는 연결 오류와 같은 HTTP 전송 계층에서 오류가 발생할 때 발생합니다.Azure::Core::Credentials::AuthenticationException-std::exception로부터 파생된 이 예외는 Azure 서비스 인증이 실패할 때 발생합니다.
서비스별 예외 유형
다른 Azure 서비스는 기본 예외 유형을 확장하여 서비스별 오류 정보를 제공합니다.
Azure::Storage::StorageException- 다른 스토리지 관련 정보로 확장합니다RequestFailedException. 이 예외에는 다음이 포함됩니다.- 스토리지 관련 오류 코드
- 응답 본문의 추가 정보
- 실패한 스토리지 작업에 대한 세부 정보
Azure::Messaging::EventHubs::EventHubsException- Event Hubs 작업과 관련된 예외입니다. 다음을 포함합니다.- 오류 조건(AMQP의 기호 값(고급 메시지 큐 프로토콜))
- 오류 설명
- 상태 코드
- 오류가 일시적인지 여부에 대한 정보
예외의 오류 정보
클래스에는 RequestFailedException 서비스 오류에 대한 다양한 정보가 포함되어 있습니다.
class RequestFailedException : public std::runtime_error {
public:
// The entire HTTP raw response
std::unique_ptr<Azure::Core::Http::RawResponse> RawResponse;
// The HTTP response code
Azure::Core::Http::HttpStatusCode StatusCode;
// The HTTP reason phrase from the response
std::string ReasonPhrase;
// The client request header (x-ms-client-request-id) from the HTTP response
std::string ClientRequestId;
// The request ID header (x-ms-request-id) from the HTTP response
std::string RequestId;
// The error code from service returned in the HTTP response
std::string ErrorCode;
// The error message from the service returned in the HTTP response
std::string Message;
/* ... constructors and other methods ... */
};
서비스별 예외는 추가 필드를 추가할 수 있습니다. 예를 들어 StorageException가 AdditionalInformation을 추가합니다.
struct StorageException final : public Azure::Core::RequestFailedException {
// Some storage-specific information in response body
std::map<std::string, std::string> AdditionalInformation;
/* ... constructors and other methods ... */
};
예외 처리 패턴 및 예제
오류 코드 사용
서비스 예외에는 오류를 처리하는 방법에 대한 결정을 내리는 데 사용할 수 있는 값이 포함되어 ErrorCode 있습니다. 스토리지 서비스의 예는 다음과 같습니다.
try {
containerClient.Delete();
}
catch (Azure::Storage::StorageException& e) {
if (e.ErrorCode == "ContainerNotFound") {
// Ignore the error if the container does not exist
}
else {
// Handle other errors here
}
}
기본 예외 처리
Azure SDK에서 예외를 처리하기 위한 기본 패턴:
try {
// Perform an Azure SDK operation
result = client.SomeOperation();
}
catch (Azure::Core::RequestFailedException const& e) {
std::cout << "Request Failed Exception happened:" << std::endl << e.what() << std::endl;
if (e.RawResponse) {
std::cout << "Error Code: " << e.ErrorCode << std::endl;
std::cout << "Error Message: " << e.Message << std::endl;
}
// Handle or rethrow as appropriate
}
catch (std::exception const& e) {
std::cout << "Other exception: " << e.what() << std::endl;
// Handle general exceptions
}
일시적 오류 처리
Event Hubs와 같은 일부 서비스는 오류가 일시적인지 여부에 대한 정보를 제공하여 다시 시도 논리를 허용합니다.
try {
// EventHubs operation
}
catch (Azure::Messaging::EventHubs::EventHubsException& e) {
if (e.IsTransient) {
// Retry the operation after a delay
}
else {
// Handle permanent failure
}
}
SDK는 일시적인 오류에 대한 내부 재시도 정책을 구현하지만 애플리케이션 코드에서 특정 사례를 처리하려고 합니다.
서비스별 오류 처리
스토리지 서비스(Blob, 파일, 큐 등)의 경우 오류 코드와 HTTP 상태 코드를 기반으로 오류를 처리할 수 있습니다.
try {
shareClient.Delete();
}
catch (Azure::Storage::StorageException& e) {
if (e.ErrorCode == "ShareNotFound") {
// Ignore the error if the file share does not exist
}
else if (e.StatusCode == Azure::Core::Http::HttpStatusCode::Conflict) {
// Handle conflict error (e.g., resource in use)
std::cout << "Conflict error: " << e.Message << std::endl;
// Check additional information
for (auto const& info : e.AdditionalInformation) {
std::cout << info.first << ": " << info.second << std::endl;
}
}
else {
// Handle other errors based on status code or error code
std::cout << "Error: " << e.Message << " (Code: " << e.ErrorCode << ")" << std::endl;
}
}
Key Vault 작업의 경우 인증 예외를 별도로 처리해야 할 수 있습니다.
try {
// Key Vault operation
}
catch (Azure::Core::Credentials::AuthenticationException const& e) {
std::cout << "Authentication Exception happened:" << std::endl << e.what() << std::endl;
// Handle authentication failure (e.g., invalid credentials)
}
catch (Azure::Core::RequestFailedException const& e) {
std::cout << "Key Vault Client Exception happened:" << std::endl << e.Message << std::endl;
// Handle Key Vault specific errors
}
스레드 안전 고려 사항
C++용 Azure SDK는 클라이언트 인스턴스 메서드가 스레드로부터 안전하고 서로 독립적임을 보장합니다. 즉, 동기화 없이 여러 스레드에서 클라이언트 인스턴스를 안전하게 사용할 수 있습니다.
스레드에서 예외를 처리할 때는 다음 사항에 유의하세요.
- 올바르게 동기화되지 않는 한 예외 개체를 스레드 간에 공유하면 안 됩니다.
- 여기에는
RequestFailedException스레드 간에 예외 정보를 전달해야 할 때 사용할 수 있는 딥 복사본을 만드는 복사 생성자가 포함됩니다.