Is it possible to override the default error page, rather than overriding them one at a time?

46 views
Skip to first unread message

Tomas Sandven

unread,
Jul 16, 2018, 8:24:21 AM7/16/18
to bottlepy
Instead of overriding one error page at a time like this:

@bottle.error(404)
def not_found_error(error):
   
return {"error": "resource not found"}

I would like to override *all* error pages, in order to prevent Bottle from sending HTML:

@bottle.error()
def error_handler(error):
   
return {"error": "unexpected error"}

And then override specific status codes after that, to provide more information:

@bottle.error(500)
def server_error(error):
   
return {"error": "server error, please try again later"}

This doesn't work however, since calling Bottle.error with no arguments defaults to code 500.

Is there any convenient way to override the default error handler, so I can prevent my JSON API from returning HTML?

I also have a question on SO about this: https://stackoverflow.com/q/51344275/388916

Tomas Sandven

unread,
Jul 16, 2018, 8:44:55 AM7/16/18
to bottlepy
After digging through the source code a bit, I quickly found a cleaner solution than the one I've been using:

class JSONBottle(bottle.Bottle):
   
def default_error_handler(self, error):
       
return json.dumps({"error": "unexpected error"})

app
= JSONBottle()

@app.error(404)
def error_404(error):
   
{"error": "resource not found"}

I'd be interested to know if this is the "recommended" way.

- Tomas
Reply all
Reply to author
Forward
0 new messages