2013-06-21

[Technology] DOMException, its nature and appropriateness for GError reporting

I've had to recently study the nature of the various DOMExceptions specified by the DOM Level 3 Core spec, to better understand whether we want to use the GError reporting system of GLib in GXml, or whether we want to use something else.  I defaulted to using GError, because the spec presents them as exceptions to be raised, and because I was used to handling libgdata errors (which are legitimately run-time errors) with GError.

The GLib Error Reporting documentation is pretty clear about when it's appropriate to use GError: basically, only when it's a run-time issue that a programmer can't reasonably anticipate.
First and foremost: GError should only be used to report recoverable runtime errors, never to report programming errors. If the programmer has screwed up, then you should use g_warning(), g_return_if_fail(), g_assert(), g_error(), or some similar facility. (Incidentally, remember that the g_error() function should only be used for programming errors, it should not be used to print any error reportable via GError.)

Examples of recoverable runtime errors are "file not found" or "failed to parse input." Examples of programming errors are "NULL passed to strcmp()" or "attempted to free the same pointer twice." These two kinds of errors are fundamentally different: runtime errors should be handled or reported to the user, programming errors should be eliminated by fixing the bug in the program. This is why most functions in GLib and GTK+ do not use the GError facility.
Below are my feelings on which DOMExceptions constitute programming errors (and shouldn't use GError) or run-time errors (and should). I look at run-time errors as consequences of the environment in which GXml is used (e.g. is it the fault of a document we're reading in, the content of which we have little control), and programming errors the direct result of a programmed call that's supplying bad data or misusing the document.

I find most of the DOMExceptions to be programming errors.  If you believe that something is more properly a run-time error and deserves GError reporting, please comment and explain why!  I am not an expert.  Like, for invalid characters, GXml might be used by a GUI where a user is entering data, and enters characters that aren't supported.  I think input checking like that should be handled in the application instead of in the GXml library, though; it shouldn't get as far as trying to actually set an attribute with bad data.  Perhaps we could provide convenience validation methods to GXml, though.  Thoughts welcome.



R: Runtime, GError
P: Programming
N: N/A

Defined Constants

N    DOMSTRING_SIZE_ERR
        If the specified range of text does not fit into a DOMString.
  we don't have our own DOMString type, we just use gchar* arrays, which don't really have 
  a fixed limit, just as much as you can alloc in a single go.

P    HIERARCHY_REQUEST_ERR
        If any Node is inserted somewhere it doesn't belong.
  this would be a programmer error, like trying to append a node to be a child of itself.

P    INDEX_SIZE_ERR
        If index or size is negative, or greater than the allowed value.
  programmer error, they should check size before accessing non-existent members of lists

P    INUSE_ATTRIBUTE_ERR
        If an attempt is made to add an attribute that is already in use elsewhere.
  programmer error

?    INVALID_ACCESS_ERR, introduced in DOM Level 2.
        If a parameter or an operation is not supported by the underlying object.
  nclear as to when this might happen; property of a document or implementation or the DOM?

?P    INVALID_CHARACTER_ERR
        If an invalid or illegal character is specified, such as in an XML name.
  I'd almost think it's a run-time error, because it probably reflects an issue with the 
  document we're working on.  Invalid characters are related to the XML version of a document,
  and which features our implementation supports.  Right now, we basically don't deal with 
  this (!).  libxml2 has version information, of course, but I'm not sure how it handles 
  invalid characters yet.  TODO: figure this out.  
  However, I think of it more as programmer error, because almost all the methods its 
  associated with are where the programmer provides a string that might contain it, rather 
  than just accessing a string already in the Document.  The other ones involve bringing
  foreign nodes into documents, and the programmer has the option of checking version 
  information and characters beforehand to ensure compatibility
    *Document.adoptNode
    Document.createAttribute
    Document.createElement
    Document.createEntityReference
    Document.createProcessingInstruction
    *Document.importNode
    Document.renameNode
    Node.prefix.set
    Element.setAttribute
    DOMImplementation.createDocument
    DOMImplementation.createDocumentType

?    INVALID_MODIFICATION_ERR, introduced in DOM Level 2.
        If an attempt is made to modify the type of the underlying object.
  Not really specified for any methods

?    INVALID_STATE_ERR, introduced in DOM Level 2.
        If an attempt is made to use an object that is not, or is no longer, usable.
  Not really specified for any methods

P    NAMESPACE_ERR, introduced in DOM Level 2.
        If an attempt is made to create or change an object in a way which is incorrect 
        with regard to namespaces.
  The result of bad input from a programmer, for qualified names.
     DOMImplementation.createDocument
     DOMImplementation.createDocumentType
     DOMImplementation.createAttributeNS
     DOMImplementation.createElementNS
     DOMImplementation.renameNode
     Node.prefix.set

P    NOT_FOUND_ERR
        If an attempt is made to reference a Node in a context where it does not exist.
  Programmer error, they're specifying the node in reference, so like with insertBefore, 
  removeChild, etc.

?RP    NOT_SUPPORTED_ERR
        If the implementation does not support the requested type of object or operation.
  We couldn't don't deal with the features of our implementation or XML versions (that's bad, 
  but oh well); not exactly sure where this would fall.  Sometimes it seems like it would be 
  a programming error (trying to adopt a Document node into another Document with adoptNode) 
  but other times, like when creating a document, I could see that being a runtime error.

?    NO_DATA_ALLOWED_ERR
        If data is specified for a Node which does not support data.
  Currently nothing raised it according to the spec, and there aren't any obvious cases 
  where I want to.  
 
?PR    NO_MODIFICATION_ALLOWED_ERR
        If an attempt is made to modify an object where modifications are not allowed.
  We currently don't have a concept of a read only node, and thus no way to check. I'm not
  sure if libxml2 has a concept of readability either.  Its common for most nodes to want to 
  raise this, so perhaps it's a real use case we should support, but even then, it feels like
  something that isn't variable at run time, and that a programmer might be able to reasonably 
  anticipate and check for.  

P    SYNTAX_ERR, introduced in DOM Level 2.
        If an invalid or illegal string is specified.
  Probably a programmer error, if they're the ones specifying strings.

P    TYPE_MISMATCH_ERR, introduced in DOM Level 3.
        If the type of an object is incompatible with the expected type of the parameter 
        associated to the object. 
  Only used by DOMConfiguration.setParameter, which we don't support.  This seems like a 
  programmer thing, anyway
    DOMConfiguration.setParameter

P    VALIDATION_ERR, introduced in DOM Level 3.
        If a call to a method such as insertBefore or removeChild would make the Node invalid 
        with respect to "partial validity", this exception would be raised and the operation 
        would not be done. This code is used in [DOM Level 3 Validation]. Refer to this 
        specification for further information.

P    WRONG_DOCUMENT_ERR
        If a Node is used in a different document than the one that created it (that doesn't 
        support it).
  Definitely a programmer error.

No comments:

Post a Comment

Labels

#General #Microblog friends #Technology life gnome music google iaido guelph fedora vegan bugs food school #GNOME linux technology #School jodo blogger gxml #Budo #Photos work web nature happy vala firefox android art Flesherton anime internet travel home open source stress kendo kosmokaryote writing animals birthday dad science security canada computers environment future cookies development german language photos programming reading sick sleep snow video winter GUADEC cell phones css fun learning love me movies people phone picasaweb ta time christmas evolution vancouver vegetarianism #Vegan Toronto ai git gsoc identity new zealand society speech vlogbrothers adventure birds communication dreams facebook google+ gseta happiness libgdata netflix night responsibility skedge stars tea tv video games wind mobile Nintendo baking cake consumerism design fedora 17 javascript memories nlp organisation photography quote tablet uoguelph Josh Ritter animalia blogging books bug encryption family humanity magic meaning memory money pidgin rain recipes speechdispatcher sushi weather #Reading Spain TAing The Frames cat chocolate cold cycling death emusic film flight genderguesser gitorious halloween health knowledge languages liv mail new years nightmares politics productivity psychology software swords the legend of zelda ubuntu web development xml xorg youtube Thanksgiving acer bc busy change conversation cooking duolingo emacs fedora 18 galaxy nexus gay rights gmail japan libxml2 martial arts materialism mozilla nerdfighteria nostalgia privacy rhythmbox sound space university upgrade valentines wahoo walking water web design Con-G Europe John Green Scott Pilgrim age animal welfare apple autumn bash blog brain brave breath of fire II calm camera canada day clothing comments confidence conservation creativity culture dance dataloss djaqua duplicity e-mail emotion english errors feminism gdom germany goals google reader gtk humour intelligence japanese laundry law light math morning moving ottawa peterborough pets philosophy pie quality research sei do kai shopping spring style summer value village vday vonage website x11 #Life New York alone anime north anxiety argument backup budo buffy business cats computer science concert copyright data loss diy eating economy education energy exercise failure fedora 19 feelings file systems flowers freedom french friend games gdata greyhound growth habits heat history house html ice cream im information java joy koryu laptop living lost microsoft mood moon muffins mystery news nz pain photo php physics pirates pizza play poverty preupgrade progress purple python rae spoon reality reflection religion rss self serialisation sharing skating social sun synergy tachi uchi testing themes thesis thinking thought thoughts transit turtles veggie challenge velociraptors violin weekend weird yum zellers API Air Canada Empathy Grimes Hank Green Hugo Jane Austen Lord of the Rings Nexus One OCUS Sudbury Trick or Eat arboretum audible autonomous automobiles beauty bike blogs browsers camping cancer canoeing celebration charity chrome cleaning colour community content corporations crafts decay decor depression depth disaster drawing epic equality experience faery fest farmer's market fedora 12 fedora 16 fedora 20 fedora 22 fedup fireworks gender ghetto ghosts glib gnome blog gnome shell google talk green hair hobocore hungry icarus instant messaging interest introspection jobs last exile luks macbook mail-notification mario meat in vitro mind mom moon festival motivation mtp ninjas oh the humanity pagans pants papers past performance perl phones picnics pitivi plastic pride pumpkin pumpkin pie quiet thrill receipts rogers rpm seminar sewing simple simplicity sleep deprivation smells soy milk speech dispatcher sports stories story telling strange streamlines swimming telephone temperature texting thrift stores time management time travel tragedy truth understanding united states urban ecosystems usability usb veganism voice volunteering webschwerver wild wireless working world yojimbo zoology Avatar: The Last Airbender Blassreiter CIS*2750 CIS*6890 Czech Republic Diablo Dresden Codak Dunedin Dutch Blitz Electric Networked Vehicle Elliott Brood Ender's Game France Fringe GNOME 3 HTC Hayao Miyazaki Mario Kart Montréal Network Manager Newfoundland Nintendo Switch Ontario Ouran Host Club Richard SVC Samsung Samurai Champloo Santa Claus Studio Ghibli TCAF US academics adb advertising aeroport algonquin amusing animal agriculture apartment ask automation awkward bad movies banana bats battery beard belladonna beta bicycle book branding breakfast brno bus buses buy nothing day cabin calgary candy cards cars catastrophe celebrate celtic chat cheap cheese childhood china chinese calendar cities clarity clean clock comics compassion compiler computer conspiracy theorists consumption context convention cookie cool cornerstone cosplay cottage country court creation cthulhu cupcakes curiosity cute dancing dark themes dbus definition deja-dup democracy despair detachment dinosaurs discomfort dns dodgeball dragon dress dust dystopia earth earth day efficiency eggs elections email enhanced history ethics evil exhausted expectations exploring ext3 ext4 fail fair trade fall fashion favourite feedly ferry focus fonts formal free friendship fruit fudge full moon furniture gaelic game boards garden gardening gee generosity genetics gimp gir gobject good google hangouts google wave government grading gratitude green roofs groups gsec guerilla gardening haircut hakama help homosexuality honesty howl hp human rights humanitarianism humility hypocrisy ice images imaqua instagram integration intellectual property internet explorer jabber jazz jelly bean jokes kernel keyboard knife labs last exile: fam the silver wing laurena lazy letters library libxml livejournal lizzie bennet loneliness loss lovely lyrics maps maturity meditation melancholy metadata microbes microfinancing microwaves moon cake morality mother music concert muso jikiden eishin ryu myth namespaces nasa nautilus nerdfighter neural networks nintendo 3ds normal normality notes obsolescence oceans open open souce open standards panasonic paper parties patches peanut butter perception personal perspectives philanthropy plants pleasant poem politeness potluck preparation problems ptp pulseaudio quidditch racism recreate redundancy relationships relax repairs resizing richard's room roomba roses rsync running sad sadness salsa samurai sanity scary schwarting seasons self-esteem self-navigating car selinux semiformal senility sensitivity sentimental sheep ships silicon motion sleeping in sms social justice software engineering solitude solutions songs soup speed spelling ssh star wars strangers stupid success sunset surreality survival skills suspense sustainability sweet sympathy symphony tardigrades tasks teaching technical communication and research methods test tests thrift tim tams time and space tired tools tracker tradition tranquillity transience trees trust tumblr twitter update user experience utopia via vihart vlog waffles warmth waste waterloo wave web comic webfonts webkit wii wiki winter is coming wizard wonder woods words xmpp yoga youth zoo #Gaming #Wishlist #anime #general 1. is anyone reading this? 1602 1984 2. you win a prize! 2008 2014 24fps 3. gimme a call to collect 404 A Short Hike All My Children Andy Griffith Argentina Armstrong House Avatar: The Legend of Korra BarTab Beach House Boston Boston Summit British Columbia Businesses C CIS*6050 Cambridge Christopher Plummer Claymore Creatures Darker than Black David Attenborough Dear Wendy Docking Station Dollhouse Earthbound England Excalibur FOMO February Fergus Final Fantasy IX Fire Emblem GError GNOME Files GSA Go Google Play Music Hunger Games I am not okay with this I believe in a thing called love I'm a wizard IRC Ikea Ireland JRR Tolkien King Arthur Lost Lagoon MIT Mac OS X Madrid March Massachusetts Matlock McGuinty Melodies of Life Merlin Michael Cera Mother Mother Mr. Tumnus Narnia Neil Gaiman New York Philharmonic Nick and Norah's Infinite Playlist Nintendorks Norns North Korea NotesFromNewYork Olympic OpenShot Orphen Orson Scott Card Oscars PEAP Pauline Johnson Pete Peterson Planet Fedora Porco Rosso Questionable Content R ROM Rent S SIM Wireless Sauble Beach Sega Sega Genesis Selenium Shakespeare She-Ra Snakes and Lattes Splatoon Star Trek Steve Grand Stranger Things ThanksLiving The Darkness The Devil is a Part-Timer The Fifth Estate The Guild The Hobbit The Stand Tianjin Tim Hortons Tolkien UI UK UX VPN Will Grayson Will Grayson Wolves in the Wall WordPerfect Xiki [General] abrt absolutism abuse academia accessibility active activism activity addiction adreama adrift adulthood advertisement air airport express airship ajax al gore alarm clock albums aldiko alice in wonderland alien alistair summerlee amateur amazon ambience ambition amy winfrey anaconda and imperfection angle angry birds anhosting animal cognition animation anon anonymity ant apache apology appearances appreciation aqualab arcade architecture arduino arrogance assassins assignments association analysis astrid asus eee top asynchronous ati attachment attitude attribution audio aural abuse authentication authenticity automake automarker avatars awesome b43 backpain backtrack3 backyard bounty bad bagel bandwidth banjo banks barbarians barefoot baseball bathroom beaches beautiful bed bees beetles being belief bellaqua benedict cumberbatch berlin bertrand russell bill gates biofabrication biology biometrics bit rot bitcoin black and white blame blockbuster bloomberg blue board games bohemian bold bon thé place bonds border boredom botany boxing day boy brain scoop brickworks broadcom broccoli browsing bubbles bubbly buildings bunnies burn bus stops butterflies buttons c# c++ cafe calendaring calligraphy camel camera obscura cameras canadian english canopy capitalism captivity careless caring cast causality cbc cedar row cello censorship certainty cgi chalk challenger changing locks chaos theory charm cherry blossoms chickadee chickens chivalry choir chopsticks chores christchurch christianity chudan church cijf cinnamon classes clif clorox clorox green works cloud cloud atlas clubs cname coca cola codeine codeviz cognition coincidence coins color comfort commons communism competence competition competitive coughing complaints completeness compliments conference configuration conflicted confusion consciousness consent conservatives conservativism console construction constructive criticism contagion contest contributing convenience corpses cough suppressants coughing coupons courageous crashes crates crayons crazy creative commons criminals crisps criticism crosscanada crowd crtc cry crying cryptic cryptozoology csh cuddles cult currency current tv curse customer service customisation cuttlefish cvs daily grind data data mining databases dating david bowie dconf debate debug symbols debugging delicious design patterns desktop desktop summit destiny dftba diet difficult digimon digital receipts disabilities disappointment discordianism discourse discoverability dispute dissection kit distraction diyode dnf doctor who doctors documentation dokuwiki doubt doughnut dpkg drab drano drano prevention dream dreaming drinking drm drowning dryers drying dtwydt ducks dvds dying dynamic typing ease easter easy ebony jewelwing ebooks ecards economics editors eeetop el paso elder neglect electronic receipts elements elitism ellen page embarrassment emily graslie emptiness empty enchant end of enterprising environmental science symposium eog epiphany eplugin equipment essentialism ether euphoria evoaqua experiment experimenting expertise extensions extortion facades faith falafel familiarity fan fancy fantasy fascism faun favicon fears fedora 11 feed me feedback festival fibonacci fiction fiddler crab field guide field identification figment figures of speech file formats finances fire fish fitness fixing flac flash light flesherton fling flexibility flour flow flying footprints forceps forgottotagit fork fortunate fortune found fragaria frameworks fraud fred penner free time freezing french fries fresh friday friend's wedding frog fspot funding funerals funny fury fuse gargoyles gdb geek geeks gf3 gi gifts gio gitlab gjs glass globalnewtgames glory gloves glue gluten gm gmo gnome keyring gnome software gnome-control-center go ninja go go transit goat gods goodbye goodfella's google assistant google books google calendar google chrome google wallet gp2x gqe grad graffiti grammar graphing graphviz grass green beaver grey county groceries growing up gtest gtg guts gvfs gvfs metadata gypsies habit hal halls hard hard drive hard drives hardship hardware harry potter hdtv heart heart break heaven 17 hemlock grove hewlett packard hijinx hiking hoaxes hobbies holidays homelessness homework honey badgers honour horatio hornblower horror hostels hosting hot house of cards hp lovecraft hugs humblebundle humbleness hunting hyperlinking hyrule i am a carpet ibm thinkpad x41 icalendar ice cream sandwich ice rain icthyology ignorant ill image image editing imagination impermanence inadequacy inaturalist inconvenience independence india individuals industry infinity ingrid michaelson inhumanity injuries ink innovation insects installation intel interactivity interlocutor internet tv invertabrates io irish irony isolation it it is indigo james bond java 13 jedi jikiden joke journalism journey judgement julian assange julie thiel justice kata kayak keys ki-ai killme kim taylor kinder kindness kirby kitchen kitzl kiva knights knots kodak koodo kung fu labels landau sacamoto late laundromat led legend lending lenovo lessons letsencrypt letstrace letter writing liberalism liberals libnotify libreoffice librpm lifehacker lilo limericks limits linksys liquid lists live wallpapers livecd liveusb loans local local food local install login london losher lots of hugs mac mini machine learning machine vision madness mae magic school bus magical maintainership majesty malaria malls mantis shrimp marine life marketing marking massages matrices maturation may seminar meat media medicine mel's diner memory leaks mental health meow mercy messaging metacity metaphor methodology mezzo forte micropayments mild mild weather military milk mindhacks minimalism misanthropy miscellany misery misfortune missed the boat missing mlp modelling moisture mold molly parker monitors monologue more cats mosquitoes moss mother's day mounting mouse moxies muffin muffinfilms mundane murder museum mushishi mushroom soup mushrooms musicals mutual funds my slumbering heart mysql nameservers nanowrimo national treasure natural language processing naturalism nausicaa navigating necessity neighbours nervous netgear network new new users newspaper hat next year ninja turtles nodelist nointernet noise noisy nominate non-root norse noses not really dying notebooks notification-daemon novels november fair nuclear war numbers numix obama obligation obliviousness obscure ocz ogg oggenc olap olive omote open formats open music openness openoffice optimisation optimism orcas orchestra oreo oreos org-mode origami oscar otr overheat owen sound package management packagekit packing paint shedding pan pancakes panda parallelism paranoia passport patents patience pattern recognition pdo peace peaceful pen pence pender penguins penmanship perfection pet rocks physical piano pickman's model picnik pidgin plugins pikmin pintsize pipelight pirate festival pizza hut plagiarism planning plans playground playlists plumbing plushies podcast poetry points pokemon polls pomplamoose positions posse post posters postmodernism potatoes potlucks power ppc practise prejudice premier pressure pretty pride and prejudice priorities private processes professionalism progressive web apps projects promise protest proud purchases pwa qt quarantine rad radeon railroad randall munroe raop rats reagan recursion recycling redhat reductionism refactoring refrigerators regret relativism release renew renfrew repetition report resolutions resolve resumes reuse reuters reviews revolution rhino rhps ricola risk road trips roar robots rockwood rot rover rtm ruby day ryu safety sanctuary sand satisfaction savages scary movies scheduling schneier scholarships scooters scp screenshots script seals search secret world of arrietty secrets seitei self-interest self-respect self-sufficiency self-worth semesters senescence sessions setbuilder settlers of catan sftp shame sheepo pistachio sheila patek shell shells sherlock holmes shipping shogun shotwell shoulder bag sigh signal sim city simafort simpsons sincerity singing sjr skill skunks sky slackware slashdot sliver small smartphones smiling snails sneezing snowboarding soccer social dance social media socis soft solemn someonesmotherwantstoadoptme song sony sophistication sorbet sorrow sparklers speed river spell spellchecking spies spilt milk splendid splendor splinter spoilers sponges sql squaresville sr ssd sshd stanley park starry night starving steampunk storage strawberries strength structured information struggle stuff stylus suburi sucks sugar super mario super mario land 3d superiority superstition surprise surprises surreal sushi surrender swings systemd systems tabs tachi uchi no kurai tail coats tameshigiri tarot taxes tears technocracy teddy bears tedtalk term termcap terror the duke the fault in our stars the hulk the human league the irregular at magic high school the onion theatre theory thingsidon'twanttodo tim berners-lee tim mcgraw timber timbre timeliness tin tin toaster todo toilets tolerance tonight toomuch touch screen touchpack tour tourniquet towels toys trac trailer translation travel buddy treestyle view trex triumf triumph trivia trouble tweak twist tx2500 tx2617 typing ugly logos umbrellas un dinaru underwold unemployment universe unlimited blade works updates upgrades uploading urban agriculture urban ecology urchins vagrancy vagrant vague but exciting valadoc validation values vampires vanilla ice variety vegetables velvet burger verb version control vi vinegar violence voip vpnc vulnerable waf wandering wanting war warm wayland weapons web hosting webcomic webcomics werewolves whales what a wonderful town whatsbetter whic are also lazer powered white spot wifi wii u wikisource will williams wings wisdom wishes wizardry wolf wonderland wordplay world cup world water day writing voice xenophobia xephyr xinput xkcd xpath yahoo yay yyz z-index

Blog Archive