django.core.serializers.get_serializer() should raise a more specific exception on invalid argument
|Reported by:||Roy Smith||Owned by:||nobody|
|Cc:||mathieu.agopian@…||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
If you call get_serializer("foo"), where "foo" is not a valid serializer type, it raises KeyError (see Ticket #15886). It should raise something more specific, such as UnknownSerializerFormat.
We're trying to build a route structure something like:
with a view that looks like:
def get_object(request, format):
serializer = django.core.serializers.get_serializer(format)
Then you can GET /foo/object.xml, /foo/object/json, etc and it all just works. The problem is, if you GET /foo/object.xyz, the get_serializer call will throw the generic KeyError, which means you need to deal with it right there (and the exception catching logic would have to be replicated in every view that used this) If it threw a more specific UnknownSerializerFormat, that could be caught in a middleware process_exception() handler, which could return HttpResponseNotFound or HttpResponseBadRequest or something like that (with an appropriate explanatory message in the body).
You don't want to catch KeyError in middleware; that's much too generic and could mask all sorts of coding errors.
Even if you wanted to keep it generic, ValueError seems more appropriate than KeyError. And it should be documented :-)
Change History (20)
comment:8 Changed 6 years ago by
|Patch needs improvement:||unset|
|Type:||Uncategorized → New feature|