Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inner function raise in Django rest API

How can I catch a 4XX series raise in inner function of an API in Django rest framework?

from rest_framework.exceptions import ValidationError


class DummyView(APIView):
    def get(self, request, id):
        if id==something:
               dummy_function_1(id)
        else:
               dummy_function_2(id)

        return Response()


def dummy_function_1():
    try:
        validate_1(id)
    except ValidationError:
        raise ValidationError()

    #do something with id
    return id

When I send a HTTP GET request, I receive a 5XX series error if exception occurs. I want to get 400 Bad Request error in response.

like image 529
Mahdi Avatar asked Aug 15 '26 13:08

Mahdi


1 Answers

After lots of effort and I don't know why, If I specify the exception type of inner function, I will get 5XX series error. so in dummy function I just wrote :

def dummy_function_1():
    try:
        validate_1(id)
    except Exception:    # just exception, Not ValidationError or other exception
        raise ValidationError()

I could get 4XX series error

like image 169
Mahdi Avatar answered Aug 17 '26 04:08

Mahdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!