Product SiteDocumentation Site

8.2. Subclassing libvirtError

It is possible to subclass the libvirtError class to add functionality. The default libvirtError does not provide any ability to either save the error information or present the information to the user. Subclassing libvirtError allows the programer the flexibility to add any functionality needed. An example of this follows:

Example 8.3. Subclassing libvirtError

#!/usr/bin/env python3
import sys
import libvirt

class report_libvirt_error(libvirt.libvirtError):
    """Subclass virError to get the last error information."""
    def __init__(self, defmsg, conn=None, dom=None, net=None, pool=None, vol=None):
        libvirt.libvirtError.__init__(self, defmsg, conn=None, dom=None, net=None, pool=None, vol=None)
        print('Default msg:   '+str(defmsg), file=sys.stderr)
        print('Error code:    '+str(self.get_error_code()), file=sys.stderr)
        print('Error domain:  '+str(self.get_error_domain()), file=sys.stderr)
        print('Error message: '+self.get_error_message(), file=sys.stderr)
        print('Error level:   '+str(self.get_error_level()), file=sys.stderr)
        if self.err[4] != None:
            print('Error string1: '+self.get_str1(), file=sys.stderr)
            print('Error string1:', file=sys.stderr)
        if self.err[5] != None:
            print('Error string2: '+self.get_str2(), file=sys.stderr)
            print('Error string2:', file=sys.stderr)
        if self.err[6] != None:
            print('Error string3: '+self.get_str3(), file=sys.stderr)
            print('Error string3:', file=sys.stderr)
        print('Error int1:    '+str(self.get_int1()), file=sys.stderr)
        print('Error int2:    '+str(self.get_int2()), file=sys.stderr)

    conn ='qemu:///system') # invalidate the parameter to force an error
except libvirt.libvirtError:
    raise report_libvirt_error('Connection error')