Django中使用中间件记录异常信息导致无响应

212 阅读1分钟

问题描述

当我在项目中使用中间件记录异常信息时,会导致logger.error下方的代码没有执行,也就没有返回响应,表现为请求一直pending中,直到Nginx返回502错误,中间件代码如下:


logger = logging.getLogger('django.request')


class AjaxException(Exception):
    def __init__(self, code, errors=None):
        self.code = code
        self.errors = errors


class AjaxExceptionMiddleware(object):

    def process_exception(self, request, exception):
        if not isinstance(exception, AjaxException):
            logger.error('Internal Server Error: %s', request.path,
                         exc_info=sys.exc_info(),
                         extra={
                             'status_code': 500,
                             'request': request
                         }
                         )
            # 上述日志
            return HttpResponse(u'服务器内部错误', status=500)
        if exception.code in ERROR_CODES:
            error_code = ERROR_CODES[exception.code]
        else:
            error_code = ERROR_CODES[ERROR_CODE_UNKNOWN]

        ret = copy.deepcopy(error_code)
        # simplicity, only have first error for browser to show
        if isinstance(exception.errors, types.StringTypes):
            ret["errmsg-detail"] = exception.errors
        else:
            ret["errmsg-detail"] = dict([(key, error[0]) for key, error in exception.errors.items()]) if exception.errors else {}
        ret['errmsg'] = force_text(ret['errmsg'])
        return HttpResponse(content=json.dumps(ret, ensure_ascii=False),
                            content_type='application/json; charset=utf-8')

DEBUG=True时,会按照中间件中的错误处理来响应,DEBUG=False时,才会无响应

解决方案

ChatGTP回答如下:

image.png

将日志等级从error换成debug/waring后,后续响应就能及时返回给客户端了。