簡體   English   中英

python-flask處理應用程序錯誤

[英]python-flask handling application errors

我建立了一個flask應用程序,然后嘗試使用errorhandler裝飾器從路由中捕獲未處理的應用程序錯誤。

我有一個看起來像這樣的main.py,

app = Flask(__name__)
api = Api(app)

api.add_resource(Ping, '/ping')

@app.errorhandler(500)
def internal_server_error(error):
    print "caught internal server error"
    return "This page does not exist", 500

路由Ping在另一個文件中,這是該文件的示例版本

class Ping(Resource):
    def get(self):

        raise
        return {}, 200

我提出了加薪嘗試並重現500內部服務器錯誤。 這是我的應用程序引發的示例錯誤

[2019-01-26 10:37:36,449] ERROR in app: Exception on /events/v1/monitoring/ping [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib64/python2.7/site-packages/flask_restful/__init__.py", line 480, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/flask/views.py", line 88, in view
    return self.dispatch_request(*args, **kwargs)
  File "/usr/local/lib64/python2.7/site-packages/flask_restful/__init__.py", line 595, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/myapi/ping.py", line 17, in get
    raise
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
127.0.0.1 - - [26/Jan/2019 10:37:36] "GET /ping HTTP/1.0" 500 -

由於我無法弄清的原因,@ app.errorhandler裝飾器無法捕獲應用程序引發的任何500個錯誤。

我認為您使用的是燒瓶式的 為了捕獲錯誤處理程序,應在配置文件中將配置參數PROPAGATE_EXCEPTIONS設置為True

Flask restful有自己的錯誤處理程序,與Flask不同。 這是摘錄:

[...]

if not isinstance(e, HTTPException) and current_app.propagate_exceptions:
    exc_type, exc_value, tb = sys.exc_info()
    if exc_value is e:
        raise
    else:
        raise e

headers = Headers()
if isinstance(e, HTTPException):
    code = e.code
    default_data = {
        'message': getattr(e, 'description', http_status_message(code))
    }
    headers = e.get_response().headers
else:
    code = 500
    default_data = {
        'message': http_status_message(code),
    }
[...]

PROPAGATE_EXCEPTIONS設置為True您至少應添加以下兩個錯誤處理程序:

@app.errorhandler(Exception)
def internal_server_error(e):
    return jsonify({'msg': 'Internal server error'}), 500

@app.errorhandler(500)
def internal_server_error_500(e):
    return jsonify({'msg': 'Internal server error'}), 500

因此,第一個將捕獲在應用程序級別引發的任何異常,甚至是您自己的自定義異常,第二個將捕獲任何500錯誤,例如在abort(500)上引發。

嘗試以下一項:

@app.errorhandler(Exception)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM