当我使用以下用户定义的异常时,我收到一条警告,即在Python 2.6中不推荐使用BaseException.message:
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
Run Code Online (Sandbox Code Playgroud)
这是警告:
DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
Run Code Online (Sandbox Code Playgroud)
这有什么问题?我需要更改什么来摆脱弃用警告?
是否有可能尝试 - 除了捕获所有仍然显示错误而不捕获每个可能的异常?我有一个案例,在每天24小时运行的脚本中,每隔几天就会发生一次异常.我不能让脚本死掉,但它们也没关系,因为只要我尝试除了一切,它都会重试.因此,当我追踪任何最后罕见的异常时,我想将它们记录到文件中以供将来调试.
例:
try:
print(555)
except:
print("type error: "+ str(the_error))
Run Code Online (Sandbox Code Playgroud)
the_error
有没有什么方法可以替换堆栈跟踪或类似的东西?
由于返回了太多的python操作ValueError
,我们如何区分它们?
示例:我希望一个iterable具有单个元素,并且我想获取它
a, = [1, 2]
:ValueError:太多值无法解压a, = []
:ValueError:值太少而无法解压我如何区分这两种情况?例如
try:
a, = lst
except ValueError as e:
if e.too_many_values:
do_this()
else:
do_that()
Run Code Online (Sandbox Code Playgroud)
I realise that in this particular case I could find a work-around using length/indexing, but the point is similar cases come up often, and I want to know if there's a general approach. I also realise I could check the error message for if 'too few' in message
but it seems a bit …
在 Python 中记录异常的最正确方法是什么?
有些人只记录e
另一个日志属性e.message
(但在某些例外情况下可能会丢失)。
一种用于str()
捕获异常的描述,但它不包含错误类型,如果没有错误类型,有时就没用。
实际上repr()
会返回错误类型和描述,但它并不那么流行(在我看到的项目中)。
还有一个相关问题:这如何影响像 Sentry 这样收集和分组错误/警报的服务。它们还应该包含一些有关具体错误的信息。
因此想再次开启这个讨论:哪种记录异常的方式最好使用?
def foo():
""" Method that can raise various types of exceptions """
1/0 # just for example
try:
foo()
except Exception as e:
logger.exception('Error occurred during execution: %s', e) # 1
logger.exception('Error occurred during execution: %s', e.message) # 2
logger.exception('Error occurred during execution: %s', str(e)) # 3
logger.exception('Error occurred during execution: %s', str(e.message)) # 4
logger.exception('Error occurred during execution: %s', repr(e)) # …
Run Code Online (Sandbox Code Playgroud) 我有以下烧瓶代码:
from flask import Flask,request,jsonify
import requests
from werkzeug.exceptions import InternalServerError, NotFound
import sys
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = "Secret!"
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/test',methods=["GET","POST"])
def test():
url = "https://httpbin.org/status/404"
try: …
Run Code Online (Sandbox Code Playgroud)