Problem:
Both handle lookups write into the same `Error` before either one is
checked, and `api_set_error()` unconditionally `xmalloc`s `err->msg`
without freeing what is already there. When both handles are invalid,
the message allocated for the window is silently overwritten by the one
for the buffer and leaked.
Solution:
Check the window before looking up the buffer. As a side effect the
reported error no longer names the buffer when the window was wrong too.
AI-assisted