from pyramid.response import Response
from sqlalchemy.exc import OperationalError, IntegrityError
import transaction

class ValidationError(Exception):
    def __init__(self, message, Errors=None):
        self.message = message
        # Call the base class constructor with the parameters it needs
        Exception.__init__(self, message)

        # Now for your custom code...
        self.Errors = Errors
    def __str__(self):
        return self.message


def TryCatchFunction(f):
    def _decorator(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except (ValidationError, ValueError, KeyError, AttributeError, TypeError, OperationalError, IntegrityError) as ex:
            transaction.abort()
            response = Response("Failed validation: {0}".format(str(ex)))
            response.status_int = 500
            return response
    return _decorator
