这个方法应该对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里了。

  1. def handle_uncaught_exception(request, resolver, exc_info):
  2. """
  3. Processing for any otherwise uncaught exceptions (those that will
  4. generate HTTP 500 responses).
  5. """
  6. # if settings.DEBUG_PROPAGATE_EXCEPTIONS:
  7. # raise
  8.  
  9. # if settings.DEBUG:
  10. # return debug.technical_500_response(request, *exc_info)
  11.  
  12. # # Return an HttpResponse that displays a friendly error message.
  13. # callback, param_dict = resolver.resolve_error_handler(500)
  14. # print(param_dict)
  15. # return callback(request, **param_dict)
  16. """
  17. Processing for any otherwise uncaught exceptions (those that will
  18. generate HTTP 500 responses). Can be overridden by subclasses who want
  19. customised 500 handling.
  20. Be *very* careful when overriding this because the error could be
  21. caused by anything, so assuming something like the database is always
  22. available would be an error.
  23. """
  24. from django.conf import settings
  25.  
  26. if settings.DEBUG_PROPAGATE_EXCEPTIONS:
  27. raise
  28. if settings.DEBUG:
  29. from django.views import debug
  30. return debug.technical_500_response(request, *exc_info)
  31. else:
  32. logger = logging.getLogger("logger")
  33. logger.error('Internal Server Error: %s', request.path,
  34. exc_info=exc_info,
  35. extra={
  36. 'status_code': 500,
  37. 'request': request
  38. }
  39. )
  40. params = request.POST
  41. userid = params.get("userid","")
  42.  
  43. #============= Code start ========== by chang
  44. # print("---------- HTTP 500 Error Msg ---------- ")
  45. # print(exc_info)
  46. # print(type(exc_info))
  47. # print(traceback.format_exc())
  48. # print("---------------------------------------- " )
  49. #
  50. # 在这里自定义自己想要数据,调用 HttpResponse方法返回,这样在DEBUG = True的状态下,在线上的情况中,我们就能看到自己想要看的错误信息,尽量不要这样操作。
  51. import time
  52. errorinfo = str(exc_info[1])
  53. error_url = request.path
  54. error_log = traceback.format_exc()
  55. error_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
  56. error = {"error": errorinfo}
  57. error["code"] = 500
  58. error["url"] = error_url
  59. error["time"] = error_time
  60. error["log"] = error_log
  61. return HttpResponse(json.dumps(error), content_type= 'application/json' , status=500)
  62. #============= Code end =========
  63. # 我已经注释掉了原有Django的方法,我觉得这样不是很友好,只有一个500,大家看起来很难受,但是线上版本还是把这些信息隐藏起来,或者恢复Django的代码。
  64. # # If Http500 handler is not installed, re-raise last exception
  65. # if resolver.urlconf_module is None:
  66. # raise (exc_info[1], None, exc_info[2])
  67. # # Return an HttpResponse that displays a friendly error message.
  68. # callback, param_dict = resolver.resolve500()
  69. # return callback(request, **param_dict)
  70. #
  71. # Return an HttpResponse that displays a friendly error message.
  72. # callback, param_dict = resolver.resolve_error_handler(500)
  73. # return callback(request, **param_dict)

  

Django自定义500的错误显示信息的更多相关文章

  1. 造成win2008 500内部错误不能显示详细错误的原因和解决方法

    造成500错误常见原因有:ASP语法出错.ACCESS数据库连接语句出错.文件引用与包含路径出错.使用了服务器不支持的组件如FSO等. 另外,对于win2008的IIS默认不显示详细出错信息的问题以下 ...

  2. form(form基础、标签渲染、错误显示 重置信息、form属性、局部钩子、全局钩子)

    form基础 Django中的Form使用时一般有两种功能: 1.生成html标签 2.验证输入内容 要想使用django提供的form,要在views里导入form模块 from django im ...

  3. Atitit.dwr3 不能显示错误详细信息的解决方案,控件显示错误详细信息的解决方案 java .net php

    Atitit.dwr3 不能显示错误详细信息的解决方案,控件显示错误详细信息的解决方案 java .net php 1. Keyword/subtitle 1 2. 使用dwr3的异常convert处 ...

  4. nginx自定义500,502,504错误页面无法跳转【转】

    1.自定一个页面,这个页面是一个链接地址可以直接访问的. 以下是nginx的配置: location / {            proxy_pass http://tomcat_app108;   ...

  5. 微信通过openID发送消息/后台post、get提交并接收数据 C# .NET 配置404,500等错误信息 连接字符串

    微信通过openID发送消息/后台post.get提交并接收数据   控制器:下面是post发送消息(微信不支持从前台发送数据,之前试过,报错,需要跨域,跨域的问题解决后还不行,最后发现之后后端提交 ...

  6. Laravel自定义错误提示,自定义异常类提示,自定义错误返回信息,自定义错误页面

    方法一 新增CustomException.php文件 App\Exceptions\CustomException.php <?php namespace App\Exceptions; us ...

  7. Atitit.dwr3 不能显示错误具体信息的解决方式,控件显示错误具体信息的解决方式 java .net php

    Atitit.dwr3 不能显示错误具体信息的解决方式,控件显示错误具体信息的解决方式 java .net php 1. Keyword/subtitle 1 2. 使用dwr3的异常convert处 ...

  8. C# .NET 配置404,500等错误信息

    <customErrors mode="On" defaultRedirect="viewAll.html"><!--所有的错误显示页--&g ...

  9. django 自定义标签和过滤器

    django 自定义标签和过滤器 Django支持自定义标签和过滤器.起初还不太重视它这项功能,但最近试了试自定义标签.发现django这个功能实在是太爽了. 首先在你项目的一个app中建立一个pyt ...

随机推荐

  1. 三、HTML元素

    嵌套的HTML元素 <!--以下实例包含了三个HTML元素,分别是<html>.<body>.<p>--> <!DOCTYPE html> ...

  2. 好用的python性能测试神器–Locust

    原文链接:https://mp.weixin.qq.com/s/9PxSPuHmucSLi_welq6uNQ 现在性能测试工具太多,根据业务不同使用,比如说我们熟悉的loadrunner.jmeter ...

  3. web.xml——Error:cvc-complex-type.2.4.a: Invalid content was found starting with element

    配置web.xml文件时报错 错误:cvc-complex-type.2.4.a: Invalid content was found starting with element 详细报错信息:cvc ...

  4. 去掉shiro登录时url里的JSESSIONID https://blog.csdn.net/aofavx/article/details/51701012

    经过查找论坛和分析源码,确认了是在ShiroHttpServletResponse里加上的. 因此继承ShiroHttpServletResponse类,覆盖相应方法,再重写 ShiroFilterF ...

  5. PHP SQL预处理

    php预处理查询 $query='insert into p1(info) values(?)'; $query2='select info from p1 where id=?'; $country ...

  6. C#中的out关键字

    在一个方法里面使用out关键字的时候这个方法中作为out关键字之后的参数会被返回出去:调用这个方法的时候需要先有一个变量来承接这个传递出来.已经被该方法改动过的参数,并且要记得传实参的时候前面带上ou ...

  7. 来自AI的Tips——情景智能

    来自AI的Tips--情景智能   上一次我们介绍了华为快服务智慧平台是什么,今天我们来侃一侃平台最有代表性的一个流量入口--情景智能(AI Tips).   首先情景智能在哪呢?大家可以拿出自己的华 ...

  8. C# 数据操作系列 - 17 Dapper ——号称可以与ADO.NET 同台飙车的ORM

    0. 前言 之前四篇介绍了一个国内开发者开发的优秀框架SqlSugar,给我们眼前一亮的感觉.这一篇,我们将试试另一个出镜率比较高的ORM框架-Dapper. Dapper是一个轻量级的ORM框架,其 ...

  9. redis使用技巧十连胜,学会工作六到飞起

    Redis 在当前的技术社区里是非常热门的.从来自 Antirez 一个小小的个人项目到成为内存数据存储行业的标准,Redis已经走过了很长的一段路. 随之而来的一系列最佳实践,使得大多数人可以正确地 ...

  10. C/C++代码优化之求两个整型的平均值

    在 C/C++ 中, 直接利用 (x + y) >> 1 来计算 \(\left\lfloor {\left( {x + y} \right)/2} \right\rfloor\) (两个 ...