Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its...
Transcript of Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its...
![Page 1: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/1.jpg)
Copyright©2014Oracleand/oritsaffiliates.Allrightsreserved.|
PL/SQL – The KISS programming language
Error Management Featuresof Oracle PL/SQL
1
![Page 2: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/2.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 2
ResourcesforOracleDatabaseDevelopers• OfficialhomeofPL/SQL- oracle.com/plsql• SQL-PL/SQLdiscussionforumonOTNhttps://community.oracle.com/community/database/developer-tools/sql_and_pl_sql
• PL/SQLandEBRblogbyBrynLlewellyn- https://blogs.oracle.com/plsql-and-ebr
• OracleLearningLibrary- oracle.com/oll• WeeklyPL/SQLandSQLquizzes,andmore- devgym.oracle.com• AskTom- asktom.oracle.com – 'nuff said• LiveSQL- livesql.oracle.com – scriptrepositoryand12/712cdatabase• oracle-developer.net - greatcontentfromAdrianBillington• oracle-base.com - greatcontentfromTimHall
![Page 3: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/3.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 3
ErrorManagementinPL/SQL• Definingexceptions• Raisingexceptions• Handlingexceptions
• Let’sstartwithquizzestotestyourknowledgeofthebasicmechanicsofexceptionhandlinginPL/SQL.
Allreferencedcodeisavailableatlivesql.oracle.com andinmydemo.zip filefromthe
PL/SQLLearningLibrary:oracle.com/oll/plsql.
![Page 4: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/4.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 44
Quiz:Whenstringsdon'tfit...(1)
DECLAREaname VARCHAR2(5);
BEGINBEGIN
aname := 'Big String';DBMS_OUTPUT.PUT_LINE (aname);
EXCEPTIONWHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('Inner block');END;DBMS_OUTPUT.PUT_LINE ('What error?');
EXCEPTIONWHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('Outer block');END;
excquiz1.sqllivesql.oracle.com "TestYourPL/SQLExceptionHandlingKnowledge"
• Whatdoyouseeafterrunningthisblock?
![Page 5: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/5.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 5
Quiz:Whenstringsdon'tfit...(2)
DECLAREaname VARCHAR2(5);
BEGINDECLARE
aname VARCHAR2(5) := 'Big String';BEGIN
DBMS_OUTPUT.PUT_LINE (aname);
EXCEPTIONWHEN VALUE_ERRORTHEN
DBMS_OUTPUT.PUT_LINE ('Inner block');END;DBMS_OUTPUT.PUT_LINE ('What error?');
EXCEPTIONWHEN VALUE_ERRORTHEN
DBMS_OUTPUT.PUT_LINE ('Outer block');END;/
excquiz2.sql
• Whatdoyouseeafterrunningthisblock?
![Page 6: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/6.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 6
DefiningExceptions• TheEXCEPTIONisalimitedtypeofdata.
– Hasjusttwoattributes:codeandmessage.– YoucanRAISEandhandleanexception,butitcannotbepassedasanargumentinaprogram.
• AssociatenameswitherrornumberswiththeEXCEPTION_INITpragma.
![Page 7: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/7.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 7
TheEXCEPTION_INITPragma
• UseEXCEPTION_INITto...– GivenamestoOracleerrorcodesforwhichnoexceptionwasdefined.– Assignanerrorcodeotherthan1toauser-definedexception(usuallyinthe-20NNNrangeusedbyRAISE_APPLICATION_ERROR).
CREATE OR REPLACE PROCEDURE upd_for_dept (dept_in IN employee.department_id%TYPE
, newsal_in IN employee.salary%TYPE)IS
e_forall_failure EXCEPTION;PRAGMA EXCEPTION_INIT (e_forall_failure, -24381);
exception_init.sqllivesql.oracle.com search"exception_init"
![Page 8: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/8.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 88
RaisingExceptions• RAISEraisesthespecifiedexceptionbyname.
– RAISE;re-raisescurrentexception.Callableonlywithintheexceptionsection.
• RAISE_APPLICATION_ERROR– Communicatesanapplicationspecificerrorbacktoanon-PL/SQLhostenvironment.– Errornumbersrestrictedtothe-20,999- -20,000range.
![Page 9: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/9.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 9
TheRAISEStatement• UseRAISEtoraiseaspecific,namedexceptionortore-raise thecurrentexception.– Raisepre-definedanduser-definedexceptions.
• "RAISE;"re-raisesthecurrentexception.– YoucanonlyuseRAISE;fromwithinanexceptionhandler.
e_forall_failure EXCEPTION;PRAGMA EXCEPTION_INIT (e_forall_failure, -24381);
BEGIN...RAISE e_forall_failure;
EXCEPTIONWHEN e_forall_failiure THEN
log_error();RAISE;
WHEN OTHERS THENlog_error();RAISE;
raise.sqlreraise.sql
![Page 10: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/10.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 10
CommunicatingApplicationErrors• WhenOracleraisesanexception,itprovidestheerrorcodeanderrormessage.
• Whenanapplication-specificerroroccurs,suchas"Accountbalancetoolow",itisuptoyou,thedeveloper,tocommunicateallnecessaryinformationtotheuser.– Thiscaninvolveanerrorcode,errormessage,orboth.
• Forthis,youmustuseRAISE_APPLICATION_ERROR.– And,really,thatistheonlytime.
![Page 11: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/11.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 1111
Definingapplication-specificmessages• Youcanraiseanapplication-specificerrorwithRAISE,butyoucannotpassbackanapplication-specificmessage thatway.
• WithRAISE_APPLICATION_ERROR,youcanissueyourown"ORA-"errormessages.– Thisbuilt-inreplacesthevaluesthatwouldnormallybereturnedwithacalltoSQLCODEandSQLERRMwithyour values.
• Thisinformationcanbedisplayedtotheuserorsenttotheerrorlog.
![Page 12: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/12.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 1212
RAISE_APPLICATION_ERRORExampleIF :NEW.birthdate > ADD_MONTHS (SYSDATE, -1 * 18 * 12)THEN
RAISE_APPLICATION_ERROR (-20070, ‘Employee must be 18.’);
END IF;
• Thiscodefromadatabasetrigger(indicatedby":NEW")showsatypical(andtypicallyproblematic)usageofRAISE_APPLICATION_ERROR.– It'sabusinessrulerequiringa"business"message.
• Typicallyproblematic:– Hard-codingoferrorcodeandmessage– Duplicationof"rule"information:18years.
employee_must_be_18.sqlLivesql.oracle.com search"raise_application_error"
![Page 13: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/13.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 13
RAISE_APPLICATION_ERRORDetails
• DefinedintheDBMS_STANDARDpackage.• Thenum argumentrange:-20,999and-20,000.
– Usesomethingelseandlose theerrormessage!
• Errormessagescanbeupto2048bytes*.– Youcanpasstoastringofupto32Kbytes,butyouwon'tbeabletogetit"out";youruserswillnotbeabletoseethefullstring.
• Thirdargumentdeterminesifthefullstack oferrorsisreturnedorjustthemostrecent.
RAISE_APPLICATION_ERROR (num binary_integer
, msg varchar2, keeperrorstack boolean default FALSE);
raise_application.sqlmax_rae_string_length.sql
errorstack.sql
![Page 14: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/14.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 14
HandlingExceptions• TheEXCEPTIONsectionconsolidatesallerrorhandlinglogicinablock.
– Butonlytrapserrorsraisedintheexecutablesectionoftheblock.
• Severalusefulfunctionsusuallycomeintoplay:– SQLCODEandSQLERRM– DBMS_UTILITY.FORMAT_CALL_STACK– DBMS_UTILITY.FORMAT_ERROR_STACK– DBMS_UTILITY.FORMAT_ERROR_BACKTRACE– Plus,newto12.1,theUTL_CALL_STACKpackage
• TheDBMS_ERRLOGpackage–QuickandeasyloggingofDMLerrors
![Page 15: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/15.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 15
SQLCODEandSQLERRM• SQLCODEreturnstheerrorcodeofthemostrecently-raisedexception.
– YoucannotcallitinsideanSQLstatement(eveninsideaPL/SQLblock).
• SQLERRMisagenericlookupfunction:returnthemessagetextforanerrorcode.– Andifyoudon'tprovideanerrorcode,SQLERRMreturnsthemessageforSQLCODE.
• But....SQLERRMmighttruncatethemessage.– Verystrange,butitispossible.– SoOraclerecommendsthatyounot usethisfunction.
sqlerrm.sqllivesql.oracle.com search"sqlerrm"
![Page 16: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/16.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 16
DBMS_UTILITY.FORMAT_CALL_STACK• The"callstack"revealsthepath takenthroughyourapplicationcodetogettothatpoint.
• Veryusefulwhenevertracingorloggingerrors.• Thestringisformattedtoshowlinenumberandprogramunitname.
– Butitdoesnotrevealthenamesofsubprograms inpackages.
callstack.sqlcallstack.pkg
livesql.oracle.com search"call_stack"
![Page 17: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/17.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 17
DBMS_UTILITY.FORMAT_ERROR_STACK• Thisbuilt-inreturnstheerrorstack inthecurrentsession.
– Possiblymorethanoneerrorinstack.
• ReturnsNULLwhenthereisnoerror.• Returnsastringofmaximumsize2000bytes(accordingtothedocumentation).
• OraclerecommendsyouusethisinsteadofSQLERRM,toreducethechanceoftruncation.
errorstack.sqlbig_error_stack.sql
livesql.oracle.com search"error_stack"
![Page 18: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/18.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 18
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE• Thebacktrace functionanswersthequestion:"Wherewasmyerrorraised?
– Priorto10.2,youcouldnotgetthisinformationfromwithinPL/SQL.
• Callitwheneveryouarelogginganerror.• Whenyoure-raiseyourexception(RAISE;)orraiseadifferentexception,subsequentBACKTRACEcallswillpointtothat line.– Sobeforeare-raise,callBACKTRACEandstorethatinformationtoavoidlosingtheoriginallinenumber.
backtrace.sqlbt.pkg
livesql.oracle.com search"backtrace"
18
![Page 19: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/19.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 19
OrUseUTL_CALL_STACK(12.1andhigher)• ThisnewpackageprovidesagranularAPItothecallstackandbacktrace.• Italsonowprovidescompletenameinformation,downtothenestedsubprogram.
• Butthebottomlineisthatgenerallyyouwillcallyourfunctionsintheexceptionsection(thruagenericerrorloggingprocedure,Ihope!)andthenwritethatinformationtoyourerrorlog.
• Whenyouneedtodiagnoseanerror,gotothelog,grabthestring,andanalyze.
12c_utl_call_stack*.sqlliveSQL.oracle.com search"utl_call_stack"
![Page 20: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/20.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 20
ContinuingPastExceptions• Whatifyouwanttocontinueprocessinginyourprogramevenifanerrorhasoccurred?
• Threeoptions...– Useanestedblock– FORALLwithSAVEEXCEPTIONS– DBMS_ERRLOG
continue_past_exception.sql
![Page 21: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/21.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 21
ExceptionhandlingandFORALL• WhenanexceptionoccursinaDMLstatement....
– ThatstatementisrolledbackandtheFORALLstops.– All(previous)successfulstatementsarenot rolledback.
• UsetheSAVEEXCEPTIONSclausetotellOracletocontinuepast exceptions,andsavetheexceptioninformationforlater.
• Thencheckthecontentsofthepseudo-collectionofrecords,SQL%BULK_EXCEPTIONS.– Twofields:ERROR_INDEXandERROR_CODE
![Page 22: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/22.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 22
FORALLwithSAVEEXCEPTIONS
• Suppress errors at the statement level.CREATE OR REPLACE PROCEDURE load_books (books_in IN book_obj_list_t)ISbulk_errors EXCEPTION;PRAGMA EXCEPTION_INIT ( bulk_errors, -24381 );
BEGINFORALL indx IN books_in.FIRST..books_in.LASTSAVE EXCEPTIONS
INSERT INTO book values (books_in(indx));EXCEPTION
WHEN bulk_errors THENFOR indx in 1..SQL%BULK_EXCEPTIONS.COUNTLOOP
log_error (SQL%BULK_EXCEPTIONS(indx).ERROR_CODE);END LOOP;
END;
Allows processing of all statements, even after an error
occurs.
Iterate through pseudo-collection of errors.
bulkexc.sqllivesql.oracle.com search "save_exceptions"
![Page 23: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/23.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 23
LOGERRORSandDBMS_ERRLOG• Usethispackage(addedinOracleDatabase10gRelease2)toenablerow-levelerrorlogging(andexceptionsuppression)forDMLstatements.– ComparetoFORALLSAVEEXCEPTIONS,whichsuppressesexceptionsatthestatementlevel.
• Createsalogtabletowhicherrorsarewritten.– Letsyouspecifymaximumnumberof"toignore"errors.
• Betterperformancethantrapping,loggingandcontinuingpastexceptions.– Exceptionhandlingisslow.
dbms_errlog.sqldbms_errlog_helper.pkg
dbms_errlog_vs_save_exceptions.sqllivesql.oracle.comsearch"logerrors"
![Page 24: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/24.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 24
LOGERRORSandDBMS_ERRLOG• SuppressDMLrow-levelerrors!• ImpactoferrorsonDMLexecution• IntroductiontoLOGERRORSfeature• Creatinganerrorlogtable• AddingLOGERRORStoyourDMLstatement• "Gotchas"intheLOGERRORSfeature• TheDBMS_ERRLOGhelperpackage
![Page 25: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/25.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 25
ImpactoferrorsonDMLexecution• AsingleDMLstatement canresultinchangestomultiplerows.• Whenanerroroccursonachangetoarow....
– Allpreviouschangesfromthatstatementarerolledback.– Nootherrowsareprocessed.– Anerrorispassedouttothecallingblock(turnsintoaPL/SQLexception).– NorollbackoncompletedDMLinthatsession.
• Usually acceptable,butwhatifyouwantto:– Avoidlosingallpriorchanges?– AvoidtheperformancepenaltyofexceptionmanagementinPL/SQL?
errors_and_dml.sqllivesql.oracle.comsearch"ExceptionsDoNotRollback"
![Page 26: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/26.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 26
Row-levelErrorSuppressioninDMLwithLOGERRORS• OncetheerrorpropagatesouttothePL/SQLlayer,itistoolate;allchangestorowshavebeenrolledback.
• TheonlywaytopreservechangestorowsistoaddtheLOGERRORSclauseinyourDMLstatement.– ErrorsaresuppressedatrowlevelwithintheSQLLayer.
• ButyouwillfirstneedtocreatedanerrorlogtablewithDBMS_ERRLOG.
![Page 27: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/27.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 27
TerminologyforLOGERRORSfeature• DMLtable:thetableonwhichDMLoperationswillbeperformed• Errorloggingtable(aka,errortable):thetablethatwillcontainhistoryoferrorsforDMLtable
• Rejectlimit:themaximumnumberoferrorsthatareacceptableforagivenDMLstatement– "Ifmorethan100errorsoccur,somethingisbadlywrong,juststop."
![Page 28: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/28.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 28
Step1.Createanerrorlogtable• CallDBMS_ERRLOG.CREATE_ERROR_LOGtocreatetheerrorloggingtableforyour"DMLtable."– Defaultname:ERR$_<your_table_name>
• Youcanspecifyalternativetablename,tablespace,owner.– NecessaryifDMLtablename>25characters!
• ThelogtablecontainsfivestandarderrorloginfocolumnsandthenacolumnforeachVARCHAR2-compatiblecolumnintheDMLtable.
dbms_errlog.sql
![Page 29: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/29.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 29
Step2:AddLOGERRORStoyourDML
• SpecifythelimitoferrorsafterwhichyouwanttheDMLstatementtostop– orUNLIMITEDtoallowittorunitscourse.
• Then...makesuretochecktheerrorlogtableafteryourunyourDMLstatement!–Oraclewillnot raiseanexceptionwhentheDMLstatementends– bigdifferencefromSAVEEXCEPTIONS.
UPDATE employeesSET salary = salary_in
LOG ERRORS REJECT LIMIT UNLIMITED;
UPDATE employeesSET salary = salary_in
LOG ERRORS REJECT LIMIT 100;
![Page 30: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/30.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 30
"Gotchas"intheLOGERRORSfeature• Thedefaulterrorloggingtableismissingsomecriticalinformation.
–Whentheerroroccurred,whoexecutedthestatement,whereitoccurredinmycode
• Errorreportingisoftenobscure:"Tableorviewdoesnotexist."• It’suptoyoutograntthenecessaryprivilegesontheerrorlogtable.
– Ifthe“DMLtable”ismodifiedfromanotherschema,thatschemamustbeabletowritetothelogtableaswell.
• UsetheDBMS_ERRLOGhelperpackagetogetaroundmanyoftheseissues.
![Page 31: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/31.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 31
TheDBMS_ERRLOGhelperpackage• Createstheerrorlogtable.• Addsthreecolumnstokeeptrackofuser,timestampandlocationincode.• Compilesatriggertopopulatetheaddedcolumns.• Createsapackagetomakeiteasiertomanagethecontentsoftheerrorlogtable.
dbms_errlog_helper.sqldbms_errlog_helper_demo.sql
livesql.oracle.comsearch"helperpackage"
![Page 32: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/32.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 32
LOGERRORS- Conclusions
• WhenexecutingmultipleDMLstatementsoraffectingmultiplerows,decideonyourerrorpolicy.– Stopatfirsterrororcontinue?
• Thendecideonthelevelofgranularityofcontinuation:statementorrow?– LOGERRORSistheonlywaytoperformrow-levelerrorsuppression.
• Makesurethatyoucheckandmanageanyerrorlogscreatedbyyourcode.
![Page 33: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/33.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 33
SomeRecommendationsforErrorManagement
• Setstandardsbeforeyoustartcoding– It'snotthekindofthingyoucaneasilyaddinlater
• Alwayscallalogprocedureinyourexceptionhandler.– Andeveryoneshouldusethesame logprocedure!
• Decidewhereinthestackyouhandleexceptions.– Alwaysattoplevelblocktoensurethatusersdon'tseeuglyerrormessags.– Ifyouneedtologlocalblockstate,handleinthatblockandre-raise.
• Justuselogger.https://github.com/OraOpenSource/Logger
![Page 34: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/34.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 34
Alwayscallalogprocedureinyourexceptionhandler
• Alwayslogerrorstoatable.• Neverinsertintoyourlogtableinthehandler.• Everyoneusesthesameprocedure.• Avoidmultipleloggingsforthesameerror.
![Page 35: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/35.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 35
Decidewhereinthestackyouhandleexceptions.
• Somesuggestthatonlythetop-levelblockshouldtrapanexception.– Theerrorutilityfunctions"remember"whereitcamefrom.
• Butyouloseinformationabouttheapplicationstateatthemomenttheexceptionwasraised.
• WhatIdo:– Alwayshandleattoplevelblocktoensurethatusersdon'tseeuglyerrormessags.– IfIneed tologlocalblockstate(parameters,variables,etc.),Ihandleinthatblockandre-raise.
![Page 36: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/36.jpg)
Copyright©2018 Oracleand/oritsaffiliates.Allrightsreserved.| 36
ErrorManagementSummary• Exceptionsraisedinthedeclarationsectionalwaysescapeunhandled.
– Considerassigningdefaultvaluesintheexecutablesectioninstead.
• CallDBMS_UTILITYorUTL_CALL_STACKfunctionswheneveryouareloggingerrorsandtracingexecution.
• SuppresserrorsatstatementlevelwithFORALL-SAVEEXCEPTIONS• SuppresserrorsatrowlevelwithLOG_ERRORS
– Butdon'tusetheERR$table"asis".
• Relyonastandard,reusableerrorloggingutility.
![Page 37: Error Management Features of PLSQL - dryfta-assets.s3 ... · Copyright © 2018Oracle and/or its affiliates. All rights reserved. | 2 Resources for Oracle Database Developers •Official](https://reader031.fdocuments.in/reader031/viewer/2022020305/5bfd96fe09d3f2fe708cd120/html5/thumbnails/37.jpg)