[英]When exception occurs should I raise or bubble it up?
I'm implementing endpoint at tornado app and have doubts how to raise and handle exceptions. 我正在龙卷风应用程序中实现端点,并且对如何引发和处理异常有疑问。
I have get method which collects all raised exceptions and logs them. 我有获取所有引发的异常并记录它们的方法。 It looks like this:
看起来像这样:
def get(self):
try:
req = self.get_request_params()
except Exception as e:
self.send_json(status_code=400, status_text=str(e))
logging.exception(str(e))
And here is get_request_params
which might throw an exception: 这是
get_request_params
,可能会引发异常:
def get_request_params(self):
try:
user_id = UUID(self.get_query_argument("user_id", None))
except ValueError:
raise ValueError("Incorrect argument value for user_id = %s" % user_id)
try:
from_date = self.get_query_argument("from", default=None)
datetime.datetime.strptime(from_date, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect argument value for from_date = %s, should be YYYY-MM-DD" % from_date)
...
There are also other request params, which checked in the same way. 还有其他请求参数,它们以相同的方式进行检查。 Looks like I'm trying to do more than necessary.
看起来我正在尝试做更多不必要的事情。 Instead of it I can have something like this:
取而代之的是,我可以这样:
def get_request_params(self):
user_id = UUID(self.get_query_argument("user_id", None))
from_date = self.get_query_argument("from", default=None)
datetime.datetime.strptime(from_date, '%Y-%m-%d')
...
In such case any exception will bubble up and will be handled at get
method. 在这种情况下,任何异常都会冒泡,并将在
get
方法中进行处理。 However, I will lost those pretty messages. 但是,我会丢失那些漂亮的消息。
So, should I be so explicit in raising exceptions or it's enough to permit thing go as they are? 因此,在提出异常方面我应该这么明确吗?还是足以让事情按原样进行?
If you catch an exception, it means you intend to do something about it, even if that something is just output a custom logging message before ignoring it or re-raising it. 如果捕获到异常,则意味着您打算对此做某事 ,即使该内容只是在忽略或重新引发它之前输出了自定义日志消息。 If the only thing you do is re-raise it, then you shouldn't have caught it in the first place.
如果您唯一要做的就是重新加注,那么您不应该首先抓住它。 (This might indicate that the class of error you are catching is too broad.)
(这可能表明您正在捕获的错误类别过于广泛。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.