With bottle/python I'm trying to get a more detailed error handling. There is a page describing a method How to return error messages in JSON with Bottle HTTPError?, but can't implement it with my project.
ara.hayrabedian's answer on the mentioned page works, but with the hope to get more details for error situations Michael's code has some charm. Only any variation I tested fails. Basically I have (out of a longer coding):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bottle import Bottle, run, static_file, view, template, \
get, post, request, debug
from bottle import route, response, error
import json
app = Bottle()
#class JSONErrorBottle(bottle.Bottle): ### just an not working alternative!?
class JSONErrorBottle(Bottle):
def default_error_handler(app, res):
bottle.response.content_type = 'application/json'
print("XXXXXXX " + json.dumps(dict(error=res.body, status_code=res.status_code)))
return json.dumps(dict(error=res.body, status_code=res.status_code))
app.install(JSONErrorBottle)
def main():
app.run(host = prefs['server'], port = prefs['port'], reloader=False)
if __name__ == '__main__':
rcode = main()
Calling an invalid page that 'default_error_handler' isn't called, just the standard bottle html error page with "Error: 404 Not Found"
The Michael's way is indeed the most "right" way. That worked for me as expected (at least with python-3.6.6 and bottle-0.12.13):
from bottle import Bottle, run, abort
import bottle, json
class JSONErrorBottle(Bottle):
def default_error_handler(self, res):
bottle.response.content_type = 'application/json'
return json.dumps(dict(error = res.body, status_code = res.status_code))
app = JSONErrorBottle()
@app.route('/hello')
def hello():
return dict(message = "Hello World!")
@app.route('/err')
def err():
abort(401, 'My Err')
run(app, host='0.0.0.0', port=8080, debug=True)
Now every error() and abort() is json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With