-
Notifications
You must be signed in to change notification settings - Fork 213
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Return status 404 instead of 500 when media not found #3552
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,7 +3,7 @@ | |
|
||
from rest_framework import status | ||
from rest_framework.decorators import action | ||
from rest_framework.exceptions import APIException | ||
from rest_framework.exceptions import APIException, NotFound | ||
from rest_framework.response import Response | ||
from rest_framework.viewsets import ReadOnlyModelViewSet | ||
|
||
|
@@ -272,7 +272,7 @@ def related(self, request, identifier=None, *_, **__): | |
raise APIException(getattr(e, "message", str(e))) | ||
# If there are no hits in the search controller | ||
except IndexError: | ||
raise APIException("Could not find items.", 404) | ||
raise NotFound | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TIL raise accepts a class object rather than an instance for lazy evaluation of the parameterless constructor 😮 https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Woah, TIL too! |
||
|
||
serializer_context = self.get_serializer_context() | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If this was supposed to be raising a 404, why wasn't it working before?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because the second parameter isn't the status code, it's the error code: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py#L99-L114. Typically this is something like a slug that identifies the error type within the status code: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py#L183-L192. This lets you have multiple distinct error types within a single semantic HTTP status code that are identifiable on the client without needing to parse the potentially arbitrary error message string.