[RFC] GErrors as Exception Objects



Here i am, breaking my own self-imposed feature freeze, but this is
pretty important.  Thanks to Emmanuele for pointing this out.

Please look this over and comment ASAP.


-=-=-

gtk2-perl maps GLib's concept of GError exceptions to Perl runtime
exceptions; that is, functions which can fail with GErrors croak and set
$@ to the message from the GError.

In general, relying on text matching on $@ strings in Perl code is shaky
at best, since the messages may change over time.  It's even worse in
gtk2-perl, because the GError messages from gtk+ and friends get
translated!

The solution: use exception objects instead of plain strings.

A GError already contains an integer error code and an error "domain"
(telling you which error codes are valid) in addition to the message. 
We can use the error domain to bless the object into a subclass of
Glib::Error, and transform the error code into the error value
nickname.  We can also find the code location, for use with the
stringification operator.

The best part: absolutely no API or ABI changes are necessary.  API
additions allow you to take advantage of this.

  eval {
     my $pixbuf = Gtk2::Gdk::Pixbuf->new_from_file ($filename);
     $image->set_from_pixbuf ($pixbuf);
  };
  if ($@) {
     print "$ \n";
     if ('' eq ref $@) {
        # don't know how to handle this
        die $@;
     } elsif ($ ->isa ('Gtk2::Gdk::Pixbuf::Error')
              and $ ->value eq 'unknown-format') {
        change_format_and_try_again ();
     } elsif ($ ->isa ('Glib::File::Error')
              and $ ->value eq 'noent') {
        change_source_dir_and_try_again ();
     }
  }


The errors are Glib::Error subclasses.  Glib::Error has these read-only
attributes:

   code - integer error code
   value - stringified error code (nickname)
   domain - error domain name
   message - readable error message
   location - " at file.pl line xx\n"

if you just try to print an error object, you get message.location, as
though it was just a plain string.


Attached are patches against HEAD which implement this.

  glib-exception-objects.patch
    changes to Glib
  gperl-gtypes.c
  gperl-gtypes.h
  GError.xs
    new files for Glib
  error.pl
    contrived example of using the exceptions.
  gtk2-exception-objects.patch
    register the three error domains defined in gtk+


Attachment: glib-exception-objects.patch
Description: Text document

Attachment: gperl-gtypes.c
Description: Text Data

Attachment: gperl-gtypes.h
Description: Text Data

Attachment: GError.xs
Description: Text document

Attachment: error.pl
Description: Text Data

Attachment: gtk2-exception-objects.patch
Description: Text Data



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]