python-3.x - 引发异常并在上层方法调用中除外
问题描述
我一直在处理我试图改进如何正确提高的例外情况。我做过这样的事情
主文件
from lib.utils import ExceptionCounter
class BarryException():
pass
candy = "hello"
color = "world"
try:
test = type(int("string"))
except Exception as err:
# My own counter for exception that sends to discord if allowed_count is 0 by calling discord.notify(msg)
ExceptionCounter().check(
exception=BarryException,
allowed_count=0,
msg={
'Title': 'Unexpected Error',
'Reason': str(err),
'Payload': str({"candy": candy, "color": color})
}
)
lib.utils
class ExceptionCounter:
"""
Counter to check if we get exceptions x times in a row.
"""
def __init__(self):
self.exception_count = {}
def check(self, exception, msg, allowed_count):
exception_name = exception.__name__
# the dict.get() method will return the value from a dict if exists, else it will return the value provided
self.exception_count[exception_name] = self.exception_count.get(exception_name, 0) + 1
if self.exception_count[exception_name] >= allowed_count:
Discord_notify(msg)
raise exception(msg)
def reset(self):
self.exception_count.clear()
然而,来自 Code Review 的人建议我这样做:
在自定义异常类型中使用上下文数据引发:
try:
...
except Exception as e:
raise BarryException('Unexpected error testing', candy=candy, color=color) from e
不要从那里打电话给 Discord;不要在那里进行异常计数;不要在那里形成不和谐的消息有效负载字典 - 只是提高。在上面的方法中,您可以排除并执行 Discord 通知。
ExceptionCounter 根本不应该知道 Discord,并且应该严格限制异常计数限制和重新引发。
我的问题是我不太了解刚刚提出的部分。在上面的方法中,您可以排除并执行 Discord 通知。- 如果有人可以解释甚至向我展示它的实际含义的示例,我将不胜感激:(
解决方案
推荐阅读
- css - 如何使用 document.querySelector 选择我的 CSS 模块类?
- php - 致命错误:第 216 行的 C:\xampp\htdocs\indotory\barang.php 中不支持的操作数类型
- php - Url 重写不会呈现带有 .js 扩展名的图像和文件
- bash - 将具有逗号分隔值的变量拆分为 bash shell 中的两个随机部分
- html - 关于rwd的布局
- c++ - c ++为什么我在if循环中的语句没有执行
- amazon-web-services - 基于路径的路由 AWS EKS
- python - 有没有办法在循环中通过更改名称来编辑变量?
- css - IOS15 中未显示视频标签
- java - 错误:无法找到或加载主类 Main(Codecademy 练习)