1

I am using exception handling classes e.g., werkzeug.exceptions.BadRequest to raise exceptions when they occur. I want to return a JSON to the user when an exception is encountered. For example,

{
'http_response': 400,
'message':'error message'
}

By default, the user gets an HTML error message like:

<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>error message</p>

Should I create a custom subclass of BadRequest and JSONify the response there? I am reluctant to do it this way because I would have to create subclasses for all the types of exceptions there are. Is there any existing library or a better way to do this?

davidism
  • 121,510
  • 29
  • 395
  • 339
smaug
  • 846
  • 10
  • 26
  • 2
    This was helpful for me : https://stackoverflow.com/questions/29332056/global-error-handler-for-any-exception – JacobIRR Jul 11 '18 at 19:24
  • @JacobIRR, thanks for the lead. But how do I have the handle_error() method used when I raise an exception anywhere in the project? I still get HTML response. Do I have to explicitly write the @errorhandlers? Or subclass the exception classes maybe? – smaug Jul 11 '18 at 19:48

0 Answers0