visit function rewritte, error handling improved