处理Python错误的助手
项目描述
errorhelpers
处理Python错误的助手。
用法
# As a decorator
@errorhelpers.expect_error(*errors, on_unexpected_error=handler)
def some_error_prone_funcion():
...
# Using with statement
with errorhelpers.expect_error(*errors, on_unexpected_error=handler):
# Some error prone operation
...
示例1: 基本用法
import pytest
import errorhelpers
with errorhelpers.expect_errors(ZeroDivisionError):
assert 4 / 2 == 2
# `ZeroDivisionError` will be re-raised.
with pytest.raises(ZeroDivisionError):
with errorhelpers.expect_errors(ZeroDivisionError):
4 / 0
# In case of other exceptions, `errorhelpers.UnexpectedError("Unexpected error")`
# will be raised instead.
with pytest.raises(errorhelpers.UnexpectedError, match="Unexpected error"):
with errorhelpers.expect_errors(ZeroDivisionError):
"a" / "b"
示例2: 自定义错误
import pytest
import errorhelpers
class CustomError(Exception):
@classmethod
def raise_(cls, msg):
def raiser(error):
print("Hiding error:", error)
raise cls(msg)
return raiser
@errorhelpers.expect_errors(
ZeroDivisionError, on_unexpected_error=CustomError.raise_("Custom error")
)
def sensitive_transaction(x, y):
return int(x) / int(y)
assert sensitive_transaction(4, "2") == 2
# `ZeroDivisionError` will be re-raised.
with pytest.raises(ZeroDivisionError):
sensitive_transaction(4, 0)
# In case of other exceptions, `CustomError` will be raised instead.
with pytest.raises(CustomError, match="Custom error"):
sensitive_transaction("a", "b")
# Hiding error: invalid literal for int() with base 10: 'a'
关闭
errorhelpers-0.2.0.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 109e0f5b9fa3b144a31870c10957a77777570f158151285ddf53860343d60cf3 |
|
MD5 | 4b6844b0a7f97b37bf50ef5ee7e6e4b2 |
|
BLAKE2b-256 | 71888db9c4c044cdb37bc88567e768048c9bf80a1a2efdf1e7cbb2328d104094 |