Django自定义500的错误显示信息

这个方法应该对Django version 2.2.4以后的版本都有效,因为我的项目是这个版本,其他版本我并没有测试。

首先找到Django的exception.py文件路径:  C:\python_37\Lib\site-packages\django\core\handlers\exception.py,要找到自己开发的Python环境的文件夹,我懒得用虚拟环境就直接使用了本地的Python环境。

之前找了很对相关的文章,踩了很多坑,发现Django version 2.2.4,这个版本已经把 handle_uncaught_exception 方法,提出来放到 exception.py里了。

def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
# if settings.DEBUG_PROPAGATE_EXCEPTIONS:
# raise

# if settings.DEBUG:
# return debug.technical_500_response(request, *exc_info)

# # Return an HttpResponse that displays a friendly error message.
# callback, param_dict = resolver.resolve_error_handler(500)
# print(param_dict)
# return callback(request, **param_dict)
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses). Can be overridden by subclasses who want
customised 500 handling.
Be *very* careful when overriding this because the error could be
caused by anything, so assuming something like the database is always
available would be an error.
"""
from django.conf import settings

if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
if settings.DEBUG:
from django.views import debug
return debug.technical_500_response(request, *exc_info)
else:
logger = logging.getLogger("logger")
logger.error('Internal Server Error: %s', request.path,
exc_info=exc_info,
extra={
'status_code': 500,
'request': request
}
)
params = request.POST
userid = params.get("userid","")

#============= Code start ========== by chang
# print("---------- HTTP 500 Error Msg ---------- ")
# print(exc_info)
# print(type(exc_info))
# print(traceback.format_exc())
# print("---------------------------------------- " )
# 
# 在这里自定义自己想要数据,调用 HttpResponse方法返回,这样在DEBUG = True的状态下,在线上的情况中,我们就能看到自己想要看的错误信息,尽量不要这样操作。
import time
errorinfo = str(exc_info[1])
error_url = request.path
error_log = traceback.format_exc()
error_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
error = {"error": errorinfo}
error["code"] = 500
error["url"] = error_url
error["time"] = error_time
error["log"] = error_log
return HttpResponse(json.dumps(error), content_type= 'application/json' , status=500)
#============= Code end =========
# 我已经注释掉了原有Django的方法,我觉得这样不是很友好,只有一个500,大家看起来很难受,但是线上版本还是把这些信息隐藏起来,或者恢复Django的代码。
# # If Http500 handler is not installed, re-raise last exception
# if resolver.urlconf_module is None:
# raise (exc_info[1], None, exc_info[2])
# # Return an HttpResponse that displays a friendly error message.
# callback, param_dict = resolver.resolve500()
# return callback(request, **param_dict)
# 
# Return an HttpResponse that displays a friendly error message.
# callback, param_dict = resolver.resolve_error_handler(500)
# return callback(request, **param_dict)

  

posted @ 2020-06-04 19:04  TimeSZ  阅读(760)  评论(0)    收藏  举报