fix error handling of middleware