Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bottle/python error handling with default_error_handler

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"

like image 467
neandr Avatar asked Oct 24 '25 17:10

neandr


1 Answers

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

like image 103
Pavel Timofeev Avatar answered Oct 26 '25 06:10

Pavel Timofeev