Exemplo n.º 1
0
def handleException(db, req, user, as_html=False):
    error_message = traceback.format_exc()
    environ = req.getEnvironment()

    environ["wsgi.errors"].write(error_message)

    if not user or not db or not user.hasRole(db, "developer"):
        url = wsgiref.util.request_uri(environ)

        x_forwarded_host = req.getRequestHeader("X-Forwarded-Host")
        if x_forwarded_host:
            original_host = x_forwarded_host.split(",")[0].strip()
            def replace_host(match):
                return match.group(1) + original_host
            url = re.sub("^([a-z]+://)[^/]+", replace_host, url)

        if user and not user.isAnonymous():
            user_string = str(user)
        else:
            user_string = "<anonymous>"

        mailutils.sendExceptionMessage(db,
            "wsgi", "\n".join(["User:   %s" % user_string,
                               "Method: %s" % req.method,
                               "URL:    %s" % url,
                               "",
                               error_message]))

        admin_message_sent = True
    else:
        admin_message_sent = False

    if not user or not db or user.hasRole(db, "developer") \
            or configuration.debug.IS_DEVELOPMENT \
            or configuration.debug.IS_TESTING:
        error_title = "Unexpected error!"
        error_message = error_message.strip()
        if as_html:
            error_message = "<p class='pre inset'>%s</p>" % htmlify(error_message)
        error_body = [error_message]
        if admin_message_sent:
            admin_message_sent = ("A message has been sent to the system "
                                  "administrator(s) with details about the "
                                  "problem.")
            if as_html:
                admin_message_sent = "<p>%s</p>" % admin_message_sent
            error_body.append(admin_message_sent)
    else:
        error_title = "Request failed!"
        error_message = ("An unexpected error occurred while handling the "
                         "request.  A message has been sent to the system "
                         "administrator(s) with details about the problem.  "
                         "Please contact them for further information and/or "
                         "assistance.")
        if as_html:
            error_message = "<p>%s</p>" % error_message
        error_body = [error_message]

    return error_title, error_body
Exemplo n.º 2
0
    def __call__(self, req, db, user):
        from operation.typechecker import TypeCheckerContext

        if user.isAnonymous() and not self.__accept_anonymous_user:
            return OperationFailureMustLogin()

        if req.method == "POST": data = req.read()
        else: data = req.getParameter("data")

        if not data: raise OperationError("no input")

        try: value = json_decode(data)
        except ValueError as error: raise OperationError("invalid input: %s" % str(error))

        try:
            self.__checker(value, TypeCheckerContext(req, db, user))
            return self.process(db, user, **value)
        except OperationError as error:
            return error
        except OperationFailure as failure:
            return failure
        except dbutils.NoSuchUser as error:
            return OperationFailure(code="nosuchuser",
                                    title="Who is '%s'?" % error.name,
                                    message="There is no user in Critic's database named that.")
        except dbutils.NoSuchReview as error:
            return OperationFailure(code="nosuchreview",
                                    title="Invalid review ID",
                                    message="The review ID r/%d is not valid." % error.id)
        except dbutils.TransactionRollbackError:
            return OperationFailure(code="transactionrollback",
                                    title="Transaction rolled back",
                                    message="Your database transaction rolled back, probably due to a deadlock.  Please try again.")
        except:
            # Decode value again since the type checkers might have modified it.
            value = json_decode(data)

            error_message = ("User: %s\nReferrer: %s\nData: %s\n\n%s"
                             % (user.name,
                                req.getReferrer(),
                                json_encode(self.sanitize(value), indent=2),
                                traceback.format_exc()))

            db.rollback()

            import mailutils
            import configuration

            if not user.hasRole(db, "developer"):
                mailutils.sendExceptionMessage(db, "wsgi[%s]" % req.path, error_message)

            if configuration.debug.IS_DEVELOPMENT or user.hasRole(db, "developer"):
                return OperationError(error_message)
            else:
                return OperationError("An unexpected error occurred.  " +
                                      "A message has been sent to the system administrator(s) " +
                                      "with details about the problem.")
Exemplo n.º 3
0
def handleException(db, req, user):
    error_message = traceback.format_exc()
    environ = req.getEnvironment()

    environ["wsgi.errors"].write(error_message)

    if not user or not user.hasRole(db, "developer"):
        url = wsgiref.util.request_uri(environ)

        x_forwarded_host = req.getRequestHeader("X-Forwarded-Host")
        if x_forwarded_host:
            original_host = x_forwarded_host.split(",")[0].strip()
            def replace_host(match):
                return match.group(1) + original_host
            url = re.sub("^([a-z]+://)[^/]+", replace_host, url)

        mailutils.sendExceptionMessage(
            "wsgi", "\n".join(["User:   %s" % (req.user or "<anonymous>"),
                               "Method: %s" % req.method,
                               "URL:    %s" % url,
                               "",
                               error_message]))

        admin_message_sent = True
    else:
        admin_message_sent = False

    if not user or user.hasRole(db, "developer") or configuration.base.IS_DEVELOPMENT:
        error_title = "Unexpected error!"
        error_body = [error_message.strip()]
        if admin_message_sent:
            error_body.append("A message has been sent to the system "
                              "administrator(s) with details about the problem.")
    else:
        error_title = "Request failed!"
        error_body = ["An unexpected error occurred while handling the request.  "
                      "A message has been sent to the system administrator(s) "
                      "with details about the problem.  Please contact them for "
                      "further information and/or assistance."]

    return error_title, error_body
Exemplo n.º 4
0
        self.__checker(value)

        try: return self.process(db, user, **value)
        except OperationError: raise
        except OperationFailure, failure: return failure
        except dbutils.NoSuchUser, error:
            return OperationFailure(code="nosuchuser",
                                    title="Who is '%s'?" % error.name,
                                    message="There is no user in Critic's database named that.")
        except:
            error_message = traceback.format_exc()

            db.rollback()

            if user.hasRole(db, "developer"):
                return OperationError(error_message)
            else:
                error_message = "User: %s\nReferrer: %s\nData: %s\n\n%s" % (user.name, req.getReferrer(), json_encode(self.sanitize(value), indent=2), error_message)
                mailutils.sendExceptionMessage("wsgi[%s]" % req.path, error_message)
                return OperationError("An unexpected error occurred.  " +
                                      "A message has been sent to the system administrator(s) " +
                                      "with details about the problem.")

    def process(self, db, user, **kwargs):
        raise OperationError, "not implemented!?!"

    def sanitize(self, value):
        """Sanitize arguments value for use in error messages or logs."""
        return value
Exemplo n.º 5
0
            db.rollback()

            if not user or user.hasRole(db, "developer"):
                title = "You broke the system again:"
                body = error_message
                body_html = "<pre>%s</pre>" % htmlify(body)
            else:
                prefix = dbutils.getURLPrefix(db)

                x_forwarded_host = req.getRequestHeader("X-Forwarded-Host")
                if x_forwarded_host: prefix = "https://" + x_forwarded_host

                url = "%s/%s?%s" % (prefix, req.path, req.query)

                mailutils.sendExceptionMessage("wsgi", (
                    "User:   %s\nMethod: %s\nPath:   %s\nQuery:  %s\nURL:    %s\n\n%s"
                    % (req.user, req.method, req.path, req.query, url,
                       error_message)))

                title = "Darn! It seems we have a problem..."
                body = "A message has been sent to the system administrator(s) with details about the problem."
                body_html = body

            if not req.isStarted():
                req.setStatus(500)
                req.setContentType("text/plain")
                req.start()
                yield "%s\n%s\n\n%s" % (title, "=" * len(title), body)
            elif req.getContentType().startswith("text/html"):
                # Close a bunch of tables, in case we're in any.  Not pretty,
                # but probably makes the end result prettier.
                yield "</table></table></table></table></div><div class='fatal'><table align=center><tr><td><h1>%s</h1><p>%s</p>" % (
Exemplo n.º 6
0
            db.rollback()

            if not user or user.hasRole(db, "developer"):
                title = "You broke the system again:"
                body = error_message
                body_html = "<pre>%s</pre>" % htmlify(body)
            else:
                prefix = dbutils.getURLPrefix(db)

                x_forwarded_host = req.getRequestHeader("X-Forwarded-Host")
                if x_forwarded_host: prefix = "https://" + x_forwarded_host

                url = "%s/%s?%s" % (prefix, req.path, req.query)

                mailutils.sendExceptionMessage("wsgi", ("User:   %s\nMethod: %s\nPath:   %s\nQuery:  %s\nURL:    %s\n\n%s"
                                                        % (req.user, req.method, req.path, req.query, url, error_message)))

                title = "Darn! It seems we have a problem..."
                body = "A message has been sent to the system administrator(s) with details about the problem."
                body_html = body

            if not req.isStarted():
                req.setStatus(500)
                req.setContentType("text/plain")
                req.start()
                yield "%s\n%s\n\n%s" % (title, "=" * len(title), body)
            elif req.getContentType().startswith("text/html"):
                # Close a bunch of tables, in case we're in any.  Not pretty,
                # but probably makes the end result prettier.
                yield "</table></table></table></table></div><div class='fatal'><table align=center><tr><td><h1>%s</h1><p>%s</p>" % (title, body_html)
    finally:
Exemplo n.º 7
0
    def __call__(self, req, db, user):
        from operation.typechecker import TypeCheckerContext

        if user.isAnonymous() and not self.__accept_anonymous_user:
            return OperationFailureMustLogin()

        if req.method == "POST": data = req.read()
        else: data = req.getParameter("data")

        if not data: raise OperationError("no input")

        try:
            value = json_decode(data)
        except ValueError as error:
            raise OperationError("invalid input: %s" % str(error))

        try:
            self.__checker(value, TypeCheckerContext(req, db, user))
            return self.process(db, user, **value)
        except OperationError as error:
            return error
        except OperationFailure as failure:
            return failure
        except dbutils.NoSuchUser as error:
            return OperationFailure(
                code="nosuchuser",
                title="Who is '%s'?" % error.name,
                message="There is no user in Critic's database named that.")
        except dbutils.NoSuchReview as error:
            return OperationFailure(
                code="nosuchreview",
                title="Invalid review ID",
                message="The review ID r/%d is not valid." % error.id)
        except dbutils.TransactionRollbackError:
            return OperationFailure(
                code="transactionrollback",
                title="Transaction rolled back",
                message=
                "Your database transaction rolled back, probably due to a deadlock.  Please try again."
            )
        except extensions.extension.ExtensionError as error:
            return OperationFailure(code="invalidextension",
                                    title="Invalid extension",
                                    message=error.message)
        except:
            # Decode value again since the type checkers might have modified it.
            value = json_decode(data)

            error_message = ("User: %s\nReferrer: %s\nData: %s\n\n%s" %
                             (user.name, req.getReferrer(),
                              json_encode(self.sanitize(value),
                                          indent=2), traceback.format_exc()))

            db.rollback()

            import mailutils
            import configuration

            if not user.hasRole(db, "developer"):
                mailutils.sendExceptionMessage(db, "wsgi[%s]" % req.path,
                                               error_message)

            if configuration.debug.IS_DEVELOPMENT or user.hasRole(
                    db, "developer"):
                return OperationError(error_message)
            else:
                return OperationError(
                    "An unexpected error occurred.  " +
                    "A message has been sent to the system administrator(s) " +
                    "with details about the problem.")
Exemplo n.º 8
0
            return self.process(db, user, **value)
        except OperationError:
            raise
        except OperationFailure, failure:
            return failure
        except dbutils.NoSuchUser, error:
            return OperationFailure(
                code="nosuchuser",
                title="Who is '%s'?" % error.name,
                message="There is no user in Critic's database named that.")
        except:
            error_message = traceback.format_exc()

            db.rollback()

            if user.hasRole(db, "developer"):
                return OperationError(error_message)
            else:
                error_message = "User: %s\nReferrer: %s\nData: %s\n\n%s" % (
                    user.name, req.getReferrer(), json_encode(
                        value, indent=2), error_message)
                mailutils.sendExceptionMessage("wsgi[%s]" % req.path,
                                               error_message)
                return OperationError(
                    "An unexpected error occurred.  " +
                    "A message has been sent to the system administrator(s) " +
                    "with details about the problem.")

    def process(self, db, user, **kwargs):
        raise OperationError, "not implemented!?!"