如何为 404 Not Found 创建自定义响应消息?

Posted

技术标签:

【中文标题】如何为 404 Not Found 创建自定义响应消息?【英文标题】:How do I create a Custom response message for 404 Not Found? 【发布时间】:2019-10-07 11:59:11 【问题描述】:

如果 get 请求接受具有字母值的 jobCategoryId,我想使用我的自定义消息创建 404 Not Found 错误响应。

请求格式:

GET /JobProfilesByCategory/:jobCategoryId

views.py:

class JobProfilesByCategoryView(generics.ListAPIView):    
"""
    A custom view to create a view for Job profile by Category. Lookup_url_kwarg fetches the jobCategoryId variable from the URL 
"""
model=JobProfiles
serializer_class = JobProfilesByCategorySerializer
lookup_url_kwarg = "jobCategoryId"

def get_queryset(self):
    jobCategoryId = self.kwargs.get(self.lookup_url_kwarg)
    print(jobCategoryId)
    if(any(c.isalpha() for c in jobCategoryId)):
        return Response("detail":"Not Found",status=status.HTTP_404_NOT_FOUND)
    else:
        queryset = JobProfiles.objects.filter(jobCategoryId=jobCategoryId)
        return queryset

urls.py:

    url(r'JobProfilesByCategory/(?P<jobCategoryId>[-\w]+$)',view=views.JobProfilesByCategoryView.as_view()),#6th API

【问题讨论】:

Django, creating a custom 500/404 error page的可能重复 【参考方案1】:

你可以使用NotFound

from rest_framework.exceptions import NotFound
...
def get_queryset(self):
    jobCategoryId = self.kwargs.get(self.lookup_url_kwarg)
    print(jobCategoryId)
    if (any(c.isalpha() for c in jobCategoryId)):
        raise NotFound("custom_key": "Custom Error Message")
    else:
        queryset = JobProfiles.objects.filter(jobCategoryId=jobCategoryId)
        return queryset

【讨论】:

以上是关于如何为 404 Not Found 创建自定义响应消息?的主要内容,如果未能解决你的问题,请参考以下文章

html Miva - 404 Not Found Page(NTFD):自定义字段重定向

怎么把一个网站页面变成404 not found?

Ajax 响应调用,404 Not Found

将正文添加到 404 Not Found 异常

GMAIL API 历史端点仅在 Android 上返回 404 not found 响应代码

Failed to load resource: the server responded with a status of 404 (Not Found)