moved defer after error check to prevent nil pointer dereference panic