Fix a bug in middleware error handling