Blog Post

Defensive Db Programming Chapter 08

,

We are slowly getting to the end of this book by Alex Kuznetsov (Blog).  You can find more on this series by looking here.  We are now discussing chapter 8 and it is a good chapter.  This chapter delves into Error Handling.

While the use of TRY…CATCH certainly is the best way to handle errors in T-SQL, it is not without difficulties. (p. 259)

In this chapter, Alex discusses some of the problems associated with error handling and demonstrates how to resolve some of those problems.  We will also see how to use XACT_ABORT.

The first key to error handling is to prepare for unanticipated failure.  That is the crux of error handling.  We anticipate certain behaviors and code for that, anything else needs to be handled through error handling so we can see what has happened.  Code sometimes fails, and queries against the data can also fail on occasion – we need to plan for those failures.

When dealing with data modifications there are occasions when using explicit transactions is necessary due to the nature of the data modification – we would want to ensure that any and all changes to the data were rolled back.  There are other times when we would want to ensure that processing halts immediately when an error is encountered.  In such a scenario, XACT_ABORT comes in useful.  Note, however, that this setting is probably better set explicitly ON or OFF depending on the needs.

A recommendation in this chapter is to use client-side error handling for all but the simplest of error handling.  Error-handling is far more robust in other languages than it is in TSQL.  This is a recommendation that I support.  Error handling in TSQL has become better over time (i.e. with the addition of the TRY…CATCH) and is quite useful for some degrees of error handling.  One particular realm where error handling in TSQL is lacking is in the area of Code-Reuse.  The TRY…CATCH must be rewritten for each stored procedure for which you wish to enable error handling.

As always, this chapter covers some of the gotchas of error handling in TSQL and gives examples on how to implement as well as circumvent some of the problems.  Check it out!!

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating