Javascript code cleanup. Concentrate the error handling in one place.