Change middleware to handle errors properly