Debian Codegraph @

azure-kusto-data/azure/kusto/data/exceptions.py

raw
1 # Copyright (c) Microsoft Corporation.
2 # Licensed under the MIT License
3 import json
4 from dataclasses import dataclass
5 from typing import List, Union, TYPE_CHECKING, Optional, Dict, Any
6
7 if TYPE_CHECKING:
8 import requests
9
10 try:
11 from aiohttp import ClientResponse
12 except ImportError:
13 # No aio installed, ignore
14 ClientResponse = None
15 pass
16
17
18 class KustoError(Exception):
19 """Base class for all exceptions raised by the Kusto Python Client Libraries."""
20
21
22 class KustoStreamingQueryError(KustoError):
23 ...
24
25
26 class KustoTokenParsingError(KustoStreamingQueryError):
27 ...
28
29
30 SEMANTIC_ERROR_STRING = "Semantic error:"
31
32
33 class KustoServiceError(KustoError):
34 """Raised when the Kusto service was unable to process a request."""
35
36 def __init__(
37 self,
38 messages: Union[str, List[dict]],
39 http_response: "Union[requests.Response, ClientResponse, None]" = None,
40 kusto_response: Optional[Dict[str, Any]] = None,
41 ):
42 super().__init__(messages)
43 self.http_response = http_response
44 self.kusto_response = kusto_response
45
46 self.message_text = messages if isinstance(messages, str) else "\n\n".join(repr(m) for m in messages)
47
48 def get_raw_http_response(self) -> "Union[requests.Response, ClientResponse, None]":
49 """Gets the http response."""
50 return self.http_response
51
52 def is_semantic_error(self) -> bool:
53 """Checks if a response is a semantic error."""
54 try:
55 return SEMANTIC_ERROR_STRING in self.message_text
56 except AttributeError:
57 return False
58
59 def has_partial_results(self) -> bool:
60 """Checks if a response exists."""
61 return self.kusto_response is not None
62
63 def get_partial_results(self) -> Optional[Dict[str, Any]]:
64 """Gets the Kusto response."""
65 return self.kusto_response
66
67
68 @dataclass
69 class OneApiError:
70 code: Optional[str] = None
71 message: Optional[str] = None
72 type: Optional[str] = None
73 description: Optional[str] = None
74 context: Optional[dict] = None
75 permanent: Optional[bool] = None
76
77 @staticmethod
78 def from_dict(obj: dict) -> "OneApiError":
79 try:
80 code = obj["code"]
81 message = obj["message"]
82 type = obj.get("@type", None)
83 description = obj.get("@message", None)
84 context = obj.get("@context", None)
85 permanent = obj.get("@permanent", None)
86 return OneApiError(code, message, type, description, context, permanent)
87 except Exception as e:
88 return OneApiError(
89 "FailedToParse", f"Failed to parse one api error. Got {repr(e)}. Full object - {json.dumps(obj)}", "FailedToParseOneApiError", "", {}, False
90 )
91
92
93 class KustoMultiApiError(KustoServiceError):
94 """
95 Represents a collection of standard API errors from kusto. Use `get_api_errors()` to retrieve more details.
96 """
97
98 def __init__(self, errors: List[dict]):
99 self.errors = KustoMultiApiError.parse_errors(errors)
100 messages = [error.description for error in self.errors]
101 super().__init__(messages[0] if len(self.errors) == 1 else messages)
102
103 def get_api_errors(self) -> List[OneApiError]:
104 return self.errors
105
106 @staticmethod
107 def parse_errors(errors: List[dict]) -> List[OneApiError]:
108 parsed_errors = []
109 for error_block in errors:
110 one_api_errors = error_block.get("OneApiErrors", None)
111 if not one_api_errors:
112 continue
113 for inner_error in one_api_errors:
114 error_dict = inner_error.get("error", None)
115 if error_dict:
116 parsed_errors.append(OneApiError.from_dict(error_dict))
117 return parsed_errors
118
119
120 class KustoApiError(KustoServiceError):
121 """
122 Represents a standard API error from kusto. Use `get_api_error()` to retrieve more details.
123 """
124
125 def __init__(self, error_dict: dict, message: str = None, http_response: "Union[requests.Response, ClientResponse, None]" = None, kusto_response=None):
126 self.error = OneApiError.from_dict(error_dict["error"])
127 super().__init__(message or self.error.description, http_response, kusto_response)
128
129 def get_api_error(self) -> OneApiError:
130 return self.error
131
132
133 class KustoNetworkError(KustoServiceError):
134 """Raised when a Kusto client fails to connect to network."""
135
136 def __init__(self, endpoint: str, client_request_id=None):
137 super().__init__(
138 "Failed to process network request for the endpoint: "
139 + endpoint
140 + ("" if client_request_id is None else ("Client Request ID:" + client_request_id))
141 )
142 self.endpoint = endpoint
143 self.client_request_id = client_request_id
144
145
146 class KustoClientError(KustoError):
147 """Raised when a Kusto client is unable to send or complete a request."""
148
149
150 class KustoBlobError(KustoClientError):
151 def __init__(self, inner: Exception):
152 self.inner = inner
153
154 def message(self) -> str:
155 return f"Failed to upload blob: {self.inner}"
156
157
158 class KustoUnsupportedApiError(KustoError):
159 """Raised when a Kusto client is unable to send or complete a request."""
160
161 @staticmethod
162 def progressive_api_unsupported() -> "KustoUnsupportedApiError":
163 return KustoUnsupportedApiError("Progressive API is unsupported - to resolve, set results_progressive_enabled=false")
164
165
166 class KustoAuthenticationError(KustoClientError):
167 """Raised when authentication fails."""
168
169 def __init__(self, authentication_method: str, exception: Exception, **kwargs):
170 super().__init__()
171 self.authentication_method = authentication_method
172 self.exception = exception
173 if "authority" in kwargs:
174 self.authority = kwargs["authority"]
175 if "kusto_uri" in kwargs:
176 self.kusto_cluster = kwargs["kusto_uri"]
177 self.kwargs = kwargs
178
179 def __str__(self):
180 return repr(self)
181
182 def __repr__(self):
183 return "KustoAuthenticationError('{}', '{}', '{}')".format(self.authentication_method, repr(self.exception), self.kwargs)
184
185
186 class KustoAioSyntaxError(SyntaxError):
187 """Raised when trying to use aio syntax without installing the needed modules"""
188
189 def __init__(self):
190 super().__init__("Aio modules not installed, run 'pip install azure-kusto-data[aio]' to leverage aio capabilities")
191
192
193 class KustoAsyncUsageError(Exception):
194 """Raised when trying to use async methods on a sync object, and vice-versa"""
195
196 def __init__(self, method: str, is_client_async: bool):
197 super().__init__("Method {} can't be called from {} client".format(method, "an asynchronous" if is_client_async else "a synchronous"))
198
199
200 class KustoThrottlingError(KustoError):
201 """Raised when API call gets throttled by the server."""
202
203 ...
204
205
206 class KustoClientInvalidConnectionStringException(KustoError):
207 """Raised when call is made to a non-trusted endpoint."""
208
209 ...
210
211
212 class KustoClosedError(KustoError):
213 """Raised when a client is closed."""
214
215 def __init__(self):
216 super().__init__("The client cannot be used because it was closed in the past.")