Refactor lock and errors