'To pass the Response from the nested function `Django REST framework`

I am using python django with Django REST framework

It can return the Reponse to the browser like this, in the views.py

from rest_framework.response import Response
    @api_view(['GET'])
    def get_by(request):
        res = {"test":"answer"}
        return Response(res)

I want to pass the Response to the browser where nested function

from rest_framework.response import Response
    @api_view(['GET'])
    def get_by(request):
        x(t)

def x():
   #error happens here!!
    res = {"error":"error happens!!"}
    return Response(res)

in this case, it is simple, I can return the error to the first function and first function can return the error Response.

but when you have three four,five nested function?

What is the best practice?



Solution 1:[1]

It should better use serializer or services and handle some validation on that.

https://www.django-rest-framework.org/api-guide/serializers/#validation

On the other side, you can develop some customized APIExcepetion and just raised them.

https://www.django-rest-framework.org/api-guide/exceptions/#api-reference

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad sadegh borouny