11

Is there a way that I can handle some sort of "catch-all" error handling in a Pyramid web app? I currently have implemented exception logging to a database (via the docs at http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/logging/sqlalchemy_logger.html) and I'll return messages to my views to put a "friendly" face on what happened.

But is there something I can implement that would show some sort of generic "Oops, you ran into a problem and we're looking into it" for anything else I'm not explicitly catching, and I could use the above error handler behind the scenes to log whatever to the database? Or, what sort of thing should I be looking for in searches?

Thanks,

edit, since I can't fit it all into a comment: . Thanks, that seems to be exactly what I'm looking for!

One thing I'm running into, I don't know if it's related or not....

So I'm implementing the SQL logger as above like so:

class SQLAlchemyHandler(logging.Handler):
    # A very basic logger that commits a LogRecord to the SQL Db
    def emit(self, record):
        trace = None
        exc = record.__dict__['exc_info']
        if exc:
            trace = traceback.format_exc(exc)
        log = Log(
            logger=record.__dict__['name'],
            level=record.__dict__['levelname'],
            trace=trace,
            msg=record.__dict__['msg'],)
        DBSession.add(log)
        DBSession.flush()
        #transaction.commit()

I had to take out the 'transaction.commit()' call and instead use .flush() because I was getting a SQLAlchemy DetachedInstanceError exception when using transaction. I think it's because I'm playing some games with passing a request to a helper function and that's where it seems to be throwing it. So it works by flushing the session. Buuuut, what happens is if I have a log.error() statement in my exception view, if an exception is actually thrown the view catches it (great!) but the log statement in the view doesn't get committed. The debugging logs in Pyramid show it being written, but never committed.

If I change the logging handler back to transaction.commit then the exceptions do get committed, but I'm back at my original problem. I think I need to focus back on what I'm doing in my helper function that's causing it in the first place, but I'm still learning SQLAlchemy in general, too. Sometimes it can be a little strange.

4

1 回答 1

13

您可以设置异常视图。例如:

@view_config(context=Exception)
def error_view(exc, request):
    #log or do other stuff to exc...
    return Response("Sorry there was an error")
于 2012-12-19T03:35:54.027 回答