If you don't want the user to see the nitty-gritty, there's no point in parsing it before showing it to them -- just don't show it at all. Trap the error and make it a generic "Something went wrong" message to the user, and dump the real message to the error log.
my $errmsg = ''; my $sql = "INSERT INTO url (url, url_id) VALUES (?, ?)"; my @bind = ( 'blah.com', 3 ); $dbh->do($sql,{},@bind); if( $dbh->err ){ warn "INSERT url FAILED: " . $dbh->errstr; $errmsg = "There was an error adding the URL"; }
If there's a few known errors, you could check for those to display a different user message:
if( $dbh->err ){ warn "INSERT url FAILED: " . $dbh->errstr; if( $dbh->err eq '123' ){ $errmsg = "Please fix ___ before adding the URL."; }elsif( $dbh->errstr =~ /not unique/ ){ $errmsg = "This URL already exists."; }else{ $errmsg = "There was an error adding the URL"; } }
Even better is to try to trap the conditions that create the error .. for example, in this case, a SELECT to see if the "url" column already exists could be done first and if a row is found toss an error to the user.
my $tmp_id = $dbh->selectrow_array("select url_id from url where url = + ?",{},$url); if( $ct ){ $errmsg = "The URL '$url' already exists w/id=$tmp_id."; return; } ... INSERT INTO ...
One more advantage of using the last two code blocks above is that you have code that's hit IFF a certain error condition arises, so if you check the test coverage it won't be 100% for these blocks unless you have explicit tests for those errors -- so it explicitly outlines the errors in the code, and makes it easier to list the possible run-time conditions to test for.

In reply to Re: Mapping database errors to user errors by davidrw
in thread Mapping database errors to user errors by jplindstrom

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.