Skip to content
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

Easy way to change behavior of BodyModel? #1265

Open
jmduke opened this issue Aug 16, 2024 · 2 comments
Open

Easy way to change behavior of BodyModel? #1265

jmduke opened this issue Aug 16, 2024 · 2 comments

Comments

@jmduke
Copy link

jmduke commented Aug 16, 2024

Hello! Thank you for django-ninja: we use it to power Buttondown's internal and external APIs, and it's been a delight.

I recently received a report from a user trying to integrate — they received the following error code:

{"detail":"Cannot parse request body"}

They needed to JSON-serialize their body, but I was curious as to where that error was propagated/populated — and found this BodyModel param (

class BodyModel(ParamModel):
).

I'd really like to be able to overwrite this error with something more actionable for users ("You passed in a FormData object, but we expected a JSON payload", that sort of thing.) Is there an easy way to configure this, or is my best option to monkey-patch get_request_data?

(Notably, that method discards the exception entirely, which is unfortunate — being able to just supply a string through the Exception, while not ideal, would still be useful.)

@lapinvert
Copy link

lapinvert commented Aug 22, 2024

I guess you just need to define a custom exception handler for this error. Have you tried it?

from json import JSONDecodeError
# (...)

api = NinjaAPI()
api.add_exception_handler(JSONDecodeError, json_decode_error_handler)

@jmduke
Copy link
Author

jmduke commented Aug 22, 2024

@lapinvert Ah, good call — that should unblock me. Still, it feels a little bit aggressive to the extent that if I have other JSONDecodeErrors in the call-chain I'd want to potentially 500 as opposed to returning an incorrect error. (Which I could then avoid by introspecting within the exception handler, but that feels very kludgy.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants