[ Team LiB ] Previous Section Next Section

Handling Errors in CGI Scripts

One of the more frustrating aspects of CGI programming is that errors in your script result in blank browser pages, and it may be difficult or impossible to find any trace of the error message. The other main problem is that your Web server may not be configured properly to find your CGI script. I use two simple tricks to track down the source of these errors. The first trick simply verifies that my script has run at all by creating an empty file somewhere on the Web server. On a UNIX system, you can put this line at the beginning of your script:

close [open /tmp/my_cgi_script_ran w]

When you aim the browser at your CGI script, it should at least create the file. If not, then the Web server cannot find your script, or it cannot find the Tclsh required by your script. Double-check your setup and the #! line in your script. On Windows, your best bet may be to use the TclHttpd Web server, which has a built-in ability to run Tcl CGI scripts. TclHttpd has other even cooler ways to generate pages, too.

If your script suddenly stops working after you've modified it, then you have introduced a programming bug. I generally put all of the script into a catch statement and print out any errors that occur. That way the errors will be displayed by the browser instead of filed into the void by your Web server. Example 3-10 shows the newguest.cgi script rewritten so the catch statement surrounds all the statements. At the end, the value of the errorInfo variable is printed out if an error has occurred:

Example 3-10 The newguest.cgi script with error handling
#!/bin/sh
# \
exec tclsh "$0" ${1+"$@"}

# Trap all errors

if {[catch {

# Use the ncgi package from tcllib to process form data

package require ncgi
ncgi::parse

# Load our data file and supporting procedures

set dir [file dirname [info script]]
set datafile [file join $dir guestbook.data]
source [file join $dir cgihacks.tcl]

# Open the datafile in append mode

set out [open $datafile a]

# Append a Tcl set command that defines the guest's entry

puts $out ""
puts $out [list set Guestbook([ncgi::value name]) \
   [list [ncgi::value url] [ncgi::value html]]]
close $out

# Return a page to the browser
Cgi_Header "Guestbook Registration Confirmed" \
    {BGCOLOR=white TEXT=black}

puts "
<TABLE BORDER=1>
<TR><TD>Name</TD>
<TD>[ncgi::value name]</TD></TR>
<TR><TD>URL</TD>
<TD><A HREF='[ncgi::value url]'>[ncgi::value url]</A></TD></TR>
<TR><TD>Extra HTML</TD>
<TD>[ncgi::value html]</TD></TR>
</TABLE>
</BODY></HTML>
"

# End of main script

} err]} {

   # Error occurred - display in the Web page

   puts "Content-Type: text/plain"
   puts ""
   puts "CGI error occurred in [info script]"
   puts $errorInfo

}
    [ Team LiB ] Previous Section Next Section