如何在REST框架中以JSON格式返回错误而不是HTML?

问题描述 投票:0回答:1

我想创建一个错误处理程序异常来返回错误 404 而不是这个 html。我怎样才能做到这一点 ?

我尝试了以下代码,但它对我不起作用

from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404

def custom_exception_handler(exc, context):
    # Call the default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP 404 handling
    if isinstance(exc, Http404):
        custom_response_data = { "error": "page not found" }
        return Response(custom_response_data, status=status.HTTP_404_NOT_FOUND)

    # Return the default response if the exception handled is not a Http404
    return response

django rest django-rest-framework django-views
1个回答
0
投票

我创造了同样的东西,它对我来说工作得很好

from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response.status_code == 404:
        response.data = {
            "success": False,
            "message": "Not found❗",
            "data": {}
        }
        return response
    elif response.status_code == 500:
        response.data = {
            "success": False,
            "message": "Internal server error! 🌐",
            "data": {}
        }
    # elif response.status_code == 400:
    #     response.data = {
    #         "success": False,
    #         "message": "Bad request!",
    #         "data": {}
    #     }
    elif response.status_code == 401:
        response.data = {
            "success": False,
            "message": "Login required! 🗝️",
            "data": {}
        }
    elif response.status_code == 403:
        response.data = {
            "success": False,
            "message": "Permission denied!",
            "data": {}
        }

    return response
© www.soinside.com 2019 - 2024. All rights reserved.