170 lines
4.4 KiB
Mojo
170 lines
4.4 KiB
Mojo
def __exit__(self, error: Error) raises -> Bool
|
|
```
|
|
|
|
Given the `Error` that occurred as an argument, the method can do any of the
|
|
following:
|
|
|
|
- Return `True` to suppress the error.
|
|
- Return `False` to re-raise the error.
|
|
- Raise a new error.
|
|
|
|
The following is an example of a context manager that suppresses only a certain
|
|
error condition and propagates all others:
|
|
|
|
```mojo title="conditional_context_mgr.mojo"
|
|
import std.time
|
|
|
|
@fieldwise_init
|
|
struct ConditionalTimer(ImplicitlyCopyable):
|
|
var start_time: Int
|
|
|
|
def __init__(out self):
|
|
self.start_time = 0
|
|
|
|
def __enter__(mut self) -> Self:
|
|
self.start_time = Int(time.perf_counter_ns())
|
|
return self
|
|
|
|
def __exit__(mut self):
|
|
var end_time = time.perf_counter_ns()
|
|
var elapsed_time_ms = round(
|
|
Float64(end_time - self.start_time) / 1e6, 3
|
|
)
|
|
print("Elapsed time:", elapsed_time_ms, "milliseconds")
|
|
|
|
def __exit__(mut self, e: Error) -> Bool:
|
|
if String(e) == "just a warning":
|
|
print("Suppressing error:", e)
|
|
self.__exit__()
|
|
return True
|
|
else:
|
|
print("Propagating error")
|
|
self.__exit__()
|
|
return False
|
|
|
|
def flaky_identity(n: Int) raises -> Int:
|
|
if (n % 4) == 0:
|
|
raise "really bad"
|
|
elif (n % 2) == 0:
|
|
raise "just a warning"
|
|
else:
|
|
return n
|
|
|
|
def main() raises:
|
|
for i in range(1, 9):
|
|
with ConditionalTimer():
|
|
print("\nBeginning execution")
|
|
|
|
print("i =", i)
|
|
time.sleep(0.1)
|
|
|
|
if i == 3:
|
|
print("continue executed")
|
|
continue
|
|
|
|
var j = flaky_identity(i)
|
|
print("j =", j)
|
|
|
|
print("Ending execution")
|
|
```
|
|
|
|
Running this example produces this output:
|
|
|
|
```output
|
|
|
|
Beginning execution
|
|
i = 1
|
|
j = 1
|
|
Ending execution
|
|
Elapsed time: 105.0 milliseconds
|
|
|
|
Beginning execution
|
|
i = 2
|
|
Suppressing error: just a warning
|
|
Elapsed time: 106.0 milliseconds
|
|
|
|
Beginning execution
|
|
i = 3
|
|
continue executed
|
|
Elapsed time: 106.0 milliseconds
|
|
|
|
Beginning execution
|
|
i = 4
|
|
Propagating error
|
|
Elapsed time: 106.0 milliseconds
|
|
Unhandled exception caught during execution: really bad
|
|
```
|
|
|
|
### Handle typed errors in `__exit__()`
|
|
|
|
The `__exit__(self, error: Error)` overload handles only `Error` values.
|
|
To handle typed errors, implement a parameterized `__exit__()` method with a
|
|
compile-time error type parameter:
|
|
|
|
```mojo
|
|
def __exit__[ErrType: AnyType](self, err: ErrType) -> Bool
|
|
```
|
|
|
|
This method receives the typed error directly, preserving its full type
|
|
information. You can use
|
|
[reflection](/docs/manual/metaprogramming/reflection/) to inspect the error
|
|
type at compile time. For example, you can:
|
|
|
|
- `reflect[ErrType].name()` — Get the error type's name as a string.
|
|
- `comptime if conforms_to(ErrType, Writable)` — Check if the error
|
|
implements `Writable`, and if so, access the error through its `Writable`
|
|
interface.
|
|
|
|
The following `ResourceGuard` example demonstrates this pattern:
|
|
|
|
```mojo
|
|
from std.reflection import *
|
|
|
|
@fieldwise_init
|
|
struct ConnectionError(Copyable, Writable):
|
|
var message: String
|
|
|
|
def write_to(self, mut writer: Some[Writer]):
|
|
writer.write("ConnectionError: ", self.message)
|
|
|
|
|
|
struct ResourceGuard(ImplicitlyCopyable):
|
|
var name: String
|
|
var suppress_errors: Bool
|
|
|
|
def __init__(out self, name: String, suppress_errors: Bool = False):
|
|
self.name = name
|
|
self.suppress_errors = suppress_errors
|
|
|
|
def __enter__(self) -> Self:
|
|
print("Acquiring:", self.name)
|
|
return self
|
|
|
|
def __exit__(self):
|
|
print("Releasing:", self.name, "(no error)")
|
|
|
|
def __exit__[ErrType: AnyType](self, err: ErrType) -> Bool:
|
|
comptime type_name = reflect[ErrType].name()
|
|
print("Releasing:", self.name)
|
|
print(" Error type:", type_name)
|
|
|
|
comptime if conforms_to(ErrType, Writable):
|
|
print(" Message:", err)
|
|
|
|
return self.suppress_errors
|
|
```
|
|
|
|
When no error occurs, `__exit__(self)` runs as usual. When a typed error occurs,
|
|
`__exit__[ErrType]()` runs instead, giving you access to the error type and
|
|
its data:
|
|
|
|
```mojo
|
|
# No error — calls __exit__(self)
|
|
with ResourceGuard("database"):
|
|
print("Working...")
|
|
|
|
# Typed error, suppressed — __exit__[ErrType] returns True
|
|
with ResourceGuard("cache", suppress_errors=True):
|
|
use_connection() # raises ConnectionError
|
|
print("Continued after suppressed error")
|