Handle errors in middleware better