【问题标题】:using Handler404 in django url dispatcher cause server error在 django url dispatcher 中使用 Handler404 导致服务器错误
【发布时间】:2019-09-29 01:00:54
【问题描述】:

我关注了这个https://stackoverflow.com/a/31381075/10087274,因为我希望当 url 不存在时出现 json 显示错误,但问题是当我在我的 url 调度程序中添加 handler404 时出现服务器错误 500 这是我的项目网址:

from django.urls import path, include
from django.conf.urls import handler404
from api.exception import custom404

handler404 = custom404

urlpatterns = [
    path('api/v1/', include('acl.urls')),
]

我的项目文件夹中有 exception.py(靠近 settings.py)包含以下内容:

from django.http import JsonResponse


def custom404(request):
    return JsonResponse({
        'status_code': 404,
        'error': 'The resource was not found'
    })

我不知道如何解决我的问题

【问题讨论】:

  • 如果您使用 DEBUG=True 运行,您是否会获得更多信息,无论是给用户还是给 Django 服务器进程的 stdout/stderr?
  • @GwynEvans 很遗憾没有,会出现 debug = true django 页面未找到

标签: django django-rest-framework django-errors


【解决方案1】:

很遗憾,您没有提供太多有关错误回溯的信息。

无论如何,我在您的代码中注意到的第一件事是,您错过了 custom404 的一个 可选参数 功能。该函数应该采用两个参数,requestexception

def custom404(request, exception=None):
    response = {
        'status_code': 404,
        'error': 'The resource was not found'
    }
    return JsonResponse(response, status=404)

参考
1.Custom Error Views

【讨论】:

  • 不幸的是,它没有回溯
  • 你试过我的答案了吗?发生了什么?
  • status=404JsonResponse()。检查我的更新答案
猜你喜欢
  • 2019-06-06
  • 2020-09-12
  • 2015-04-10
  • 1970-01-01
  • 2013-04-14
  • 2022-01-25
  • 2011-01-01
  • 2012-09-04
  • 2014-01-20
相关资源
最近更新 更多