0
# DNS Exceptions
1
2
Comprehensive exception classes for handling DNS errors and operational failures. All dnspython exceptions inherit from DNSException, providing consistent error handling patterns across the library.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Core exception classes that form the foundation of dnspython's error handling system.
9
10
```python { .api }
11
class DNSException(Exception):
12
"""
13
Abstract base class shared by all dnspython exceptions.
14
15
Supports both old/compatible mode (args only) and new/parametrized
16
mode (kwargs only) for consistent error reporting.
17
"""
18
19
class FormError(DNSException):
20
"""DNS message is malformed."""
21
22
class SyntaxError(DNSException):
23
"""Text input is malformed."""
24
25
class UnexpectedEnd(SyntaxError):
26
"""Text input ended unexpectedly."""
27
28
class TooBig(DNSException):
29
"""The DNS message is too big."""
30
31
class Timeout(DNSException):
32
"""The DNS operation timed out."""
33
```
34
35
### Resolver Exceptions
36
37
Specific exception classes for DNS resolution operations and query failures.
38
39
```python { .api }
40
class NXDOMAIN(DNSException):
41
"""
42
The DNS query name does not exist.
43
44
Provides access to the canonical name through canonical_name() method
45
and supports both single and multiple query name scenarios.
46
"""
47
48
def canonical_name(self) -> str:
49
"""Get the canonical name if available from CNAME chains."""
50
51
class YXDOMAIN(DNSException):
52
"""The DNS query name exists when it should not."""
53
54
class NoAnswer(DNSException):
55
"""
56
The DNS response contains no answer to the question.
57
58
This can occur when a name exists but has no records of the
59
requested type, or when DNSSEC validation fails.
60
"""
61
62
class NoNameservers(DNSException):
63
"""No non-broken nameservers are available to answer the question."""
64
65
class NotAbsolute(DNSException):
66
"""Raised if an absolute DNS name is required but a relative name was provided."""
67
68
class NoRootSOA(DNSException):
69
"""Raised if for some reason there is no SOA RR at the DNS root name."""
70
71
class NoMetaqueries(DNSException):
72
"""Raised if a metaquery is attempted with a resolver that forbids them."""
73
```
74
75
### DNSSEC Exceptions
76
77
Exception classes specific to DNSSEC validation and cryptographic operations.
78
79
```python { .api }
80
class ValidationFailure(DNSException):
81
"""
82
DNSSEC validation has failed.
83
84
Contains details about why validation failed and which keys
85
or signatures were involved in the failure.
86
"""
87
88
class UnsupportedAlgorithm(DNSException):
89
"""
90
A DNSSEC algorithm is not supported.
91
92
Raised when encountering DNSSEC keys or signatures using
93
cryptographic algorithms not supported by the current
94
configuration or available cryptographic libraries.
95
"""
96
```
97
98
### Zone and Transfer Exceptions
99
100
Exception classes for zone file operations and zone transfer failures.
101
102
```python { .api }
103
class BadZone(DNSException):
104
"""The DNS zone is malformed."""
105
106
class NoSOA(BadZone):
107
"""The DNS zone has no SOA RR at its origin."""
108
109
class NoNS(BadZone):
110
"""The DNS zone has no NS RRset at its origin."""
111
112
class UnknownOrigin(DNSException):
113
"""The DNS zone's origin is unknown."""
114
```
115
116
### Message and Wire Format Exceptions
117
118
Exception classes for DNS message parsing and wire format operations.
119
120
```python { .api }
121
class ShortHeader(FormError):
122
"""The DNS packet passed to from_wire() is too short to contain a header."""
123
124
class TrailingJunk(FormError):
125
"""The DNS packet passed to from_wire() has trailing junk."""
126
127
class UnknownHeaderField(BadHeader):
128
"""The header field name is unknown."""
129
130
class BadHeader(FormError):
131
"""The DNS message header is malformed."""
132
```
133
134
## Usage Examples
135
136
### Basic Exception Handling
137
138
```python
139
import dns.resolver
140
import dns.exception
141
142
try:
143
result = dns.resolver.query('nonexistent.example.com', 'A')
144
except dns.resolver.NXDOMAIN as e:
145
print(f"Domain does not exist: {e}")
146
# Get canonical name if available from CNAME chain
147
try:
148
canonical = e.canonical_name()
149
print(f"Canonical name: {canonical}")
150
except:
151
print("No canonical name available")
152
153
except dns.resolver.NoAnswer as e:
154
print(f"No answer for query: {e}")
155
156
except dns.resolver.Timeout as e:
157
print(f"Query timed out: {e}")
158
159
except dns.exception.DNSException as e:
160
print(f"DNS error: {e}")
161
```
162
163
### Handling Network and Transport Errors
164
165
```python
166
import dns.query
167
import dns.exception
168
169
try:
170
response = dns.query.udp(query_message, '8.8.8.8', timeout=5)
171
except dns.exception.Timeout:
172
print("UDP query timed out, trying TCP")
173
try:
174
response = dns.query.tcp(query_message, '8.8.8.8', timeout=10)
175
except dns.exception.Timeout:
176
print("TCP query also timed out")
177
178
except dns.exception.FormError as e:
179
print(f"Malformed DNS message: {e}")
180
181
except dns.exception.TooBig as e:
182
print(f"Response message too large: {e}")
183
```
184
185
### Zone Operation Error Handling
186
187
```python
188
import dns.zone
189
import dns.exception
190
191
try:
192
zone = dns.zone.from_file('example.com.zone', 'example.com.')
193
except dns.zone.NoSOA:
194
print("Zone file missing required SOA record")
195
except dns.zone.NoNS:
196
print("Zone file missing required NS records")
197
except dns.zone.BadZone as e:
198
print(f"Malformed zone file: {e}")
199
except dns.exception.SyntaxError as e:
200
print(f"Zone file syntax error: {e}")
201
```
202
203
### DNSSEC Validation Error Handling
204
205
```python
206
import dns.dnssec
207
import dns.exception
208
209
try:
210
dns.dnssec.validate(rrset, rrsigset, keys)
211
print("DNSSEC validation successful")
212
except dns.dnssec.ValidationFailure as e:
213
print(f"DNSSEC validation failed: {e}")
214
except dns.dnssec.UnsupportedAlgorithm as e:
215
print(f"Unsupported DNSSEC algorithm: {e}")
216
```
217
218
## Exception Hierarchy
219
220
```python { .api }
221
DNSException (Exception)
222
├── FormError
223
│ ├── ShortHeader
224
│ ├── TrailingJunk
225
│ └── BadHeader
226
│ └── UnknownHeaderField
227
├── SyntaxError
228
│ └── UnexpectedEnd
229
├── TooBig
230
├── Timeout
231
├── NXDOMAIN
232
├── YXDOMAIN
233
├── NoAnswer
234
├── NoNameservers
235
├── NotAbsolute
236
├── NoRootSOA
237
├── NoMetaqueries
238
├── ValidationFailure
239
├── UnsupportedAlgorithm
240
├── BadZone
241
│ ├── NoSOA
242
│ └── NoNS
243
└── UnknownOrigin
244
```
245
246
## Types
247
248
```python { .api }
249
class DNSException(Exception):
250
"""Base exception class with support for parametrized error messages."""
251
msg: Optional[str]
252
kwargs: Dict[str, Any]
253
254
def __init__(self, *args, **kwargs): ...
255
def __str__(self) -> str: ...
256
257
class NXDOMAIN(DNSException):
258
"""Non-existent domain exception with canonical name support."""
259
260
def canonical_name(self) -> str:
261
"""Return canonical name from CNAME chain if available."""
262
263
class Timeout(DNSException):
264
"""Timeout exception with elapsed time information."""
265
266
def __init__(self, timeout: float = None): ...
267
```