from webob import Response


class JsonErrorMiddleware:
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        try:
            return self.app(environ, start_response)
        except Exception as e:
            response = Response()
            response.status_code = 500
            response.json_body = {
                "error": "Internal Server Error",
                "message": str(e)
            }
            response.content_type = "application/json"
            return response(environ, start_response)