chapter seven

7 Error handling and logging

 

This chapter covers:

  • An idea of exceptions in Haskell and when to use them
  • Several exception handling mechanisms
  • Designing exception handling in pure and impure code

Programmers want to control everything within their programs. In Haskell, we can do that via type discipline and reasoning about functions behavior. Unfortunately, communication with the outer world sets limits to that control:

  • When readiang a file, we can never be sure in advance whether it exists or not;
  • Even if it does exist, we have no guarantee its content matches our expectations;
  • While we are fetching a web page, network connection may break;
  • Acquiring a resource (even memory allocation!) may fail.

How should we react? When can we get information about the problems we’ve got? When do we know how to address them? Is it the same time or not? Should we halt our application completely? Is it possible to figure out how to proceed instead? These questions have to be answered in every application.

In this chapter, we discuss an idea of an exception and exception handling mechanisms for getting around the problems mentioned above. We also cover logging as an essential tool for recording information on what is going wrong at runtime.

7.1 Overview of error handling mechanisms in Haskell

Exceptions in Haskell are traditionally complicated. There are at least two reasons for that:

7.1.1 An idea of exceptions

7.1.2 To use or not to use

7.1.3 Programmable exceptions vs GHC runtime exceptions

7.2 Programmable exceptions in monad stacks

7.2.1 The ExceptT monad transformer

7.2.2 Example: evaluating RPN expressions

7.3 GHC runtime exceptions

7.3.1 An idea of extensible exceptions

7.3.2 Throwing exceptions

7.3.3 Catching exceptions

7.4 Example: Accessing web APIs and GHC exceptions

7.4.1 Application components

7.4.2 Exceptions handling strategies

7.5 Logging

7.5.1 An overview of the monad-logger library

7.5.2 Introducing logging with monad-logger into the suntimes project

7.6 Summary