# Buggy code
def _lookup(self, name, *args, **kwargs):
    instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self)

    if instance is not None:
        wantlist = kwargs.pop("wantlist", False)

        from ansible.utils.listify import listify_lookup_plugin_terms

        loop_terms = listify_lookup_plugin_terms(
            terms=args,
            templar=self,
            loader=self._loader,
            fail_on_undefined=True,
            convert_bare=False,
        )
        # safely catch run failures per #5059
        try:
            ran = instance.run(
                loop_terms, variables=self._available_variables, **kwargs
            )
        except (AnsibleUndefinedVariable, UndefinedError) as e:
            raise AnsibleUndefinedVariable(e)
        except Exception as e:
            if self._fail_on_lookup_errors:
                raise
            ran = None

        if ran:
            from ansible.vars.unsafe_proxy import UnsafeProxy, wrap_var

            if wantlist:
                ran = wrap_var(ran)
            else:
                try:
                    ran = UnsafeProxy(",".join(ran))
                except TypeError:
                    if isinstance(ran, list) and len(ran) == 1:
                        ran = wrap_var(ran[0])
                    else:
                        ran = wrap_var(ran)

        return ran
    else:
        raise AnsibleError("lookup plugin (%s) not found" % name)


# Traceback (KeyError)
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 124, in run
res = self._execute()
File "/usr/local/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 401, in _execute
self._task.post_validate(templar=templar)
File "/usr/local/lib/python2.7/site-packages/ansible/playbook/task.py", line 246, in post_validate
super(Task, self).post_validate(templar)
File "/usr/local/lib/python2.7/site-packages/ansible/playbook/base.py", line 317, in post_validate
value = templar.template(getattr(self, name))
File "/usr/local/lib/python2.7/site-packages/ansible/template/__init__.py", line 358, in template
d[k] = self.template(variable[k], preserve_trailing_newlines=preserve_trailing_newlines, fail_on_undefined=fail_on_undefined, overrides=overrides)
File "/usr/local/lib/python2.7/site-packages/ansible/template/__init__.py", line 330, in template
result = self._do_template(variable, preserve_trailing_newlines=preserve_trailing_newlines, escape_backslashes=escape_backslashes, fail_on_undefined=fail_on_undefined, overrides=overrides)
File "/usr/local/lib/python2.7/site-packages/ansible/template/__init__.py", line 494, in _do_template
res = j2_concat(rf)
File "<template>", line 8, in root
File "/usr/local/lib/python2.7/site-packages/jinja2/runtime.py", line 196, in call
return __obj(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/ansible/template/__init__.py", line 415, in _lookup
ran = instance.run(loop_terms, variables=self._available_variables, **kwargs)
File "/Users/jdavila/Tech/sandbox/lookup_plugins/dumb.py", line 10, in run
value = mydict['bar']
KeyError: 'bar'

fatal: [localhost]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}

# Fixed code
def _lookup(self, name, *args, **kwargs):
    instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self)

    if instance is not None:
        wantlist = kwargs.pop("wantlist", False)

        from ansible.utils.listify import listify_lookup_plugin_terms

        loop_terms = listify_lookup_plugin_terms(
            terms=args,
            templar=self,
            loader=self._loader,
            fail_on_undefined=True,
            convert_bare=False,
        )
        # safely catch run failures per #5059
        try:
            ran = instance.run(
                loop_terms, variables=self._available_variables, **kwargs
            )
        except (AnsibleUndefinedVariable, UndefinedError) as e:
            raise AnsibleUndefinedVariable(e)
        except Exception as e:
            if self._fail_on_lookup_errors:
                raise AnsibleError(
                    "An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s"
                    % (name, type(e), e)
                )
            ran = None

        if ran:
            from ansible.vars.unsafe_proxy import UnsafeProxy, wrap_var

            if wantlist:
                ran = wrap_var(ran)
            else:
                try:
                    ran = UnsafeProxy(",".join(ran))
                except TypeError:
                    if isinstance(ran, list) and len(ran) == 1:
                        ran = wrap_var(ran[0])
                    else:
                        ran = wrap_var(ran)

        return ran
    else:
        raise AnsibleError("lookup plugin (%s) not found" % name)