Added exception handling to middleware.