Most of this code is adaptated from libgpg-error error handling implementation.
