Add global error handler

Ensures that any errors raised in the agent are logged and returned consistently.