added error handling to middleware