Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 271
stackoverflowuser95 Avatar asked Jan 24 '14 05:01

stackoverflowuser95


People also ask

How exceptions are caught in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

Which exception catch all exceptions in Python?

Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.


1 Answers

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)
like image 124
micimize Avatar answered Oct 02 '22 01:10

micimize