Skip to content
This repository has been archived by the owner on Jul 15, 2024. It is now read-only.

Commit

Permalink
2.0.1
Browse files Browse the repository at this point in the history
1.Fixed a parameter annotation error, of `TryExcept.etype`.
2.Raise the stack level of the exception class name warning information, in `GqylpyException.__getattr__`.
3.Removed additional function descriptions from readme file.

1.修复了 `tryexception .etype` 中一个参数注释错误。
2.提高了 `GqylpyException.__getattr__` 警告信息的堆栈级别。
3.从自述文件中移除附加功能描述。
  • Loading branch information
2018-11-27 committed Apr 22, 2023
1 parent 8756de6 commit 09dad08
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 99 deletions.
88 changes: 1 addition & 87 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@

> 在执行 `raise` 语句的同时创建异常类,无需事先定义异常类,方便快捷。例如,你想抛出一个名为 `NotUnderstandError` 的异常,
> 导入 `import gqylpy_exception as ge` 后直接执行 `raise ge.NotUnderstandError` 即可。
>
> `gqylpy-exception` 还提供了两个处理异常的装饰器:
> - `TryExcept`: 截获被装饰的函数中引发的异常,并将异常信息输出到终端,不是抛出。
> - `Retry`: 同上,并会尝试重新执行,通过参数控制次数,在达到最大次数后抛出异常。
<kbd>pip3 install gqylpy_exception</kbd>


### 使用 `gqylpy_exception` 创建异常类
###### 使用 `gqylpy_exception` 创建异常类
```python
import gqylpy_exception as ge

Expand All @@ -37,85 +33,3 @@ from gqylpy_exception import AnError
raise AnError(...)
```
另外,`gqylpy_exception` 不会重复创建异常类,创建过的异常类将存入 `ge.__history__` 字典,当你再次创建时从这个字典中取值。


### 使用装饰器 `TryExcept` 处理函数中引发的异常
```python
from gqylpy_exception import TryExcept

@TryExcept(ValueError)
def func():
int('a')
```
默认的处理流程是将异常简要信息输出到终端。当然,也可以输出到文件或做其它处理,通过参数控制:
```python
def TryExcept(
etype: Union[ExceptionTypes],
*,
silent_exc: Optional[bool] = None,
raw_exc: Optional[bool] = None,
logger: Optional[ExceptionLogger] = None,
ereturn: Optional[Any] = None,
ecallback: Optional[ExceptionCallback] = None,
eexit: Optional[bool] = None
):
...
```
__参数 `etype`__<br>
要处理哪种异常,使用元祖传入多个。

__参数 `silent_exc`__<br>
设为 `True` 将静默处理异常,没有任何输出。

__参数 `raw_exc`__<br>
设为 `True` 将输出完整的异常信息,注意其优先级低于 `silent_exc`

__参数 `logger`__<br>
接收一个日志记录器对象,`TryExcept` 希望使用日志记录器输出异常信息,它调用日志记录器的 `error` 方法。<br>
缺省情况下使用 `sys.stderr` 输出异常信息。

__参数 `ereturn`__<br>
若被装饰的函数中引发了异常,将返回此参数,默认为 `None`。<br>
它在某些可以设定非 `None` 默认返回值的函数中非常好用。

__参数 `ecallback`__<br>
接收一个可调用对象,若被装饰的函数中引发了异常将调用它。<br>
这个可调用对象还需接收多个参数:引发的异常对象,被装饰的函数对象,被装饰的函数的所有参数。

__参数 `eexit`__<br>
设为 `True` 将在引发异常后抛出 `SystemExit(4)`,如果有 `ecallback` 则会先执行 `ecallback`


### 使用装饰器 `Retry` 重试函数中引发的异常
```python
from gqylpy_exception import Retry

@Retry(count=3, cycle=1)
def func():
int('a')
```
若被装饰的函数中引发了异常,会尝试重新执行被装饰的函数,默认重试 `Exception` 及其子类的所有异常。
像上面这样调用 `Retry(count=3, cycle=1)` 表示最大执行3次,每次间隔1秒。完整的参数如下:
```python
def Retry(
etype: Optional[ExceptionTypes] = None,
*,
count: Optional[int] = inf,
cycle: Optional[Union[int, float]] = 0,
silent_exc: Optional[bool] = None,
raw_exc: Optional[bool] = None,
logger: Optional[ExceptionLogger] = None
):
...
```
`Retry` 继承 `TryExcept`,你可以在 `TryExcept` 中找到参数说明,但注意 `Retry` 调用日志记录器的 `warning` 方法。

结合 `TryExcept` 使用,既能重试异常又能处理异常:
```python
from gqylpy_exception import TryExcept, Retry

@TryExcept(ValueError)
@Retry(count=3, cycle=1)
def func():
int('a')
```
24 changes: 13 additions & 11 deletions gqylpy_exception/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
>>> import gqylpy_exception as ge
>>> raise ge.AnError(...)
@version: 2.0
@version: 2.0.1
@author: 竹永康 <gqylpy@outlook.com>
@source: https://github.com/gqylpy/gqylpy-exception
Expand Down Expand Up @@ -57,7 +57,7 @@ class GqylpyError(Exception):


def TryExcept(
etype: Union[ExceptionTypes],
etype: ExceptionTypes,
*,
silent_exc: Optional[bool] = None,
raw_exc: Optional[bool] = None,
Expand All @@ -67,8 +67,8 @@ def TryExcept(
eexit: Optional[bool] = None
) -> Callable:
"""
`TryExcept` is a decorator, handles exceptions raised by the function it
decorates.
`TryExcept` is a decorator (is an additional function of `gqylpy_exception`
), handles exceptions raised by the function it decorates.
>>> @TryExcept(ValueError)
>>> def func():
Expand Down Expand Up @@ -104,9 +104,9 @@ def Retry(
logger: Optional[ExceptionLogger] = None
) -> Callable:
"""
`Retry` is a decorator, retries exceptions raised by the function it
decorates. When an exception is raised in function decorated, try to
re-execute the function decorated.
`Retry` is a decorator (is an additional function of `gqylpy_exception`),
retries exceptions raised by the function it decorates. When an exception is
raised in function decorated, try to re-execute the function decorated.
>>> @Retry(count=3, cycle=1)
>>> def func():
Expand Down Expand Up @@ -143,8 +143,9 @@ async def TryExceptAsync(
ecallback: Optional[ExceptionCallback] = None,
eexit: Optional[bool] = None
) -> Callable:
"""`TryExceptAsync` is a decorator, handles exceptions raised by the
asynchronous function it decorates."""
"""`TryExceptAsync` is a decorator (is an additional function of
`gqylpy_exception`), handles exceptions raised by the asynchronous function
it decorates."""
warnings.warn(
f'will be deprecated soon, replaced to {TryExcept}.', DeprecationWarning
)
Expand All @@ -168,8 +169,9 @@ async def RetryAsync(
raw_exc: Optional[bool] = None,
logger: Optional[ExceptionLogger] = None
) -> Callable:
"""`RetryAsync` is a decorator, retries exceptions raised by the
asynchronous function it decorates."""
"""`RetryAsync` is a decorator (is an additional function of
`gqylpy_exception`), retries exceptions raised by the asynchronous function
it decorates."""
warnings.warn(
f'will be deprecated soon, replaced to {Retry}.', DeprecationWarning
)
Expand Down
2 changes: 1 addition & 1 deletion gqylpy_exception/g exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __getattr__(self, ename: str) -> Type['GqylpyError']:
if ename[-5:] != 'Error':
warnings.warn(
f'strange exception class "{ename}", exception class name '
'should end with "Error".', UserWarning
'should end with "Error".', UserWarning, stacklevel=2
)
eclass = self.__history__[ename] = type(
ename, (self.GqylpyError,), {'__module__': 'builtins'}
Expand Down

0 comments on commit 09dad08

Please sign in to comment.