Only schedule Close() if err is non-nil

This fixes a nil dereference error