Error Handling

Importance of Error Handling

Decent error handling is important because:

The die Function

The die function should be used to indicate a fatal error and abort the build. Its parameters should be the message to display.

Although die will work with no parameters, a short message should always be provided to ease error identification. This is especially important when a function can die in multiple places.

Ebuild helpers from EAPI 4 and onwards automatically die on failure. Some eclass-provided functions will automatically die upon failure, others will not. Developers should check the eclass reference when in doubt.

Sometimes displaying additional error information beforehand can be useful. Use eerror to do this. See Messages.

It's best to use || die too often than too little.

die and Subshells

The following code will not work as expected, since the die is inside a subshell:

[[ -f foorc ]] && ( update_foorc || die "Couldn't update foorc!" )

The correct way to rewrite this is to use an if block:

if [[ -f foorc ]] ; then
    update_foorc || die "Couldn't update foorc!"

When using pipes, a subshell is introduced, so the following is unsafe:

cat list | while read file ; do epatch ${file} ; done

Using input redirection (see Abuse of cat) avoids this problem:

while read file ; do epatch ${file} ; done < list

The assert Function and $PIPESTATUS

When using pipes, simple conditionals and tests upon $? will not correctly detect errors occurring in anything except the final command in the chain. To get around this, bash provides the $PIPESTATUS variable, and portage provides the assert function to check this variable.

bunzip2 "${DISTDIR}/${VIM_RUNTIME_SNAP}" | tar xf

If you need the gory details of $PIPESTATUS, see the bash manpage. Most of the time, assert is enough.