Search code examples
pythonpluginswsgibottlemiddleware

Bottle middleware to catch exceptions of a certain type?


Given this simple Bottle code:

def bar(i):
    if i%2 == 0:
        return i
    raise MyError

@route('/foo')
def foo():
    try:
        return bar()
    except MyError as e:
        response.status_code = e.pop('status_code')
        return e

How would one write Bottle middleware so the same exception handling is done implicitly, so that code like this can work identically to above:

@route('/foo')
def foo():
    return bar()

Solution

  • You can do this elegantly with a plugin leveraging abort:

    from bottle import abort
    
    def error_translation(func):
        def wrapper(*args,**kwargs):
            try:
                func(*args,**kwargs)
            except ValueError as e:
                abort(400, e.message)
        return wrapper
    
    app.install(error_translation)