Move defer to right place
Fix link not delete in case of error