首页 > 解决方案 > Python 捕获 Tornado Web 服务器中的所有错误

问题描述

我将 Tornado 作为异步应用程序服务器(不是 WSGI)运行。我需要捕获所有已定义的 api 端点/Tornado 处理程序的所有服务器错误(如500 Internal Server Error), so I added thisErrorHandler` 类(根据此处

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import handlers as th
from tornado import web

class ErrorHandler(web.RequestHandler):
    """Generates an error response with status_code for all requests."""

    def write_error(self, status_code, **kwargs):
        print('In get_error_html. status_code: ', status_code)
        if status_code in [403, 404, 500, 503]:
            self.write('Error %s' % status_code)
        else:
            self.write('BOOM!')

    def prepare(self):
        print('In prepare...')
        raise Exception('Error!')

def application():

    handlers = [

        # Catch all Error handler
        (r"/", ErrorHandler),

        (r'/data', th.customHandler)
    ]

    settings = dict()
    return web.Application(handlers, **settings)

但它不起作用。当调用导致 500 错误的/data端点时,customHandler我仍然得到一个

<html>
<title>500: Internal Server Error</title>

<body>500: Internal Server Error</body>

</html>

标签: python-3.xtornado

解决方案


推荐阅读