chapter seven

7 Exceptions 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:

  • Whenever we read a file, we can’t 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, our program may be a subject to a broken network connection;
  • Acquiring a scarce resource can fail due to a shortage.

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 will need to be answered in every application.

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

7.1  Overview of exceptions in Haskell

Exceptions in Haskell is a traditionally complicated topic. There are several reasons for that:

7.1.1  To use or not to use

7.1.2  An idea of exceptions

7.1.3  Programmable exceptions in monad stacks

7.1.4  GHC runtime exceptions

7.2  Evaluating expressions with programmable exceptions

7.2.1  The ExceptT monad transformer and the Except monad

7.2.2  Throwing exceptions

7.2.3  Catching exceptions within the monad stack

7.3  Accessing web APIs and GHC exceptions

7.3.1  Application components

7.3.2  Exceptions handling strategies

7.4  Logging

7.4.1  An overview of the monad-logger library

7.4.2  Introducing logging with monad-logger into the suntimes project

7.5  Summary