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

Custom JSON-based HTTPError #740

Open
joarleymoraes opened this issue Mar 24, 2016 · 5 comments
Open

Custom JSON-based HTTPError #740

joarleymoraes opened this issue Mar 24, 2016 · 5 comments

Comments

@joarleymoraes
Copy link

Hey guys,

I have been using Falcon for some REST-API projects. And I have the following use case I wanted an input from you guys. I would like to respond to clients custom json-based error messages as follow:

{
"error":"A error occurred"
"type":"database.error"
"code":13
}

I know I could build error responses from scratch (using a Middleware, for example), but it would be great if I could accomplish it by elegantly raising an HTTPError like:

raise HTTPBadRequest(title, desc, code)

The problem with this solution is basically the field names that seems not appropriate for error message (title, desc, code). Is there any recommended way to change those names ? Or maybe extend HTTPError somehow ?

Thanks in advance.
Joarley

@kgriffs
Copy link
Member

kgriffs commented Apr 26, 2016

Hi @joarleymoraes, there are a few ways you could approach this. The first one would be to raise a custom error type (or child thereof) and then serialize it with a custom error handler. Another approach would be to inherit from HTTPError but only use the fields from the base class that you need, adding additional ones in the child class. In this second approach, you would also need to implement a custom error serializer to render the JSON result.

@kgriffs kgriffs added this to the On Deck (Non-Breaking Changes) milestone Apr 26, 2016
@joarleymoraes
Copy link
Author

Thanks @kgriffs. I ended up implementing custom error handler together with a JSON-Translator middleware to prepare the response.

@vvvhung
Copy link

vvvhung commented Aug 15, 2017

I found an example. Allow me to post here for anyone who still looking for one:

https://stackoverflow.com/questions/41103069/custom-response-during-falcon-middleware-exception/45685353#45685353

@rwagnergit
Copy link

Thenks @vvvhung. Struggled with this for days. Your solution is exactly what I was looking for.

@vytas7
Copy link
Member

vytas7 commented Apr 14, 2021

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

No branches or pull requests

5 participants