【发布时间】:2015-10-01 12:50:36
【问题描述】:
我正在学习Django Rest Framework,也是 django 的新手。当客户端将访问未找到的资源时,我想在 json 中返回自定义 404 错误。
我的urls.py 看起来像这样:
urlpatterns = [
url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin')
]
其中我只有一个资源,可以通过URI访问,http://localhost:8000/mailer/
现在,当客户端访问像 http://localhost:8000/ 这样的任何其他 URI 时,API 应该返回像这样的 404-Not Found 错误:
{
"status_code" : 404
"error" : "The resource was not found"
}
如果合适,请使用正确的代码 sn-ps 提出一些答案。
【问题讨论】:
-
我正在使用 Django REST framework exceptions 中描述的
custom_exception_handler方法来捕获将在 function_view 或 class_views 中引发的异常。
标签: python django rest django-rest-framework