Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t GHC use my displayException method?

Tags:

I have the following Haskell program where I customize the displayException method for human-friendly display of an exception:

import Control.Exception
import Data.Typeable

data MyException = MyException String
                 deriving (Show, Typeable)

instance Exception MyException where
  displayException (MyException e) = "oops! " ++ e

main = throw $ MyException "something's wrong"

But when I run it under GHC 8.6.4, I get

myprog.hs: MyException "something's wrong"

instead of the expected

myprog.hs: oops! something's wrong

Why isn’t my displayException method being used?

like image 236
Vasiliy Faronov Avatar asked Apr 03 '19 08:04

Vasiliy Faronov


1 Answers

GHC's runtime does not use displayException to report catched exceptions to the user.

You need to provide custom Show instance instead:

data MyException = MyException String
    deriving Typeable

instance Show MyException where
    show (MyException e) = "oops! " ++ e

instance Exception MyException

displayException was added years ago in order to have different methods for exception serialization (show) and reporting to the user (displayException).

In the mentioned discussion I found this reply by Edward Kmett and it seems like a good reason for GHC RTS not to use displayException.

My experience is that whenever someone writes a "helpful" Show instance it winds up anything but.

Why?

What happens when you print a list of them, or they occur deeper in a larger structure?

Invariably I wind up with things like a bag of your exceptions in an async exception wrapper or someone's position type in my data structure [...]

"Helpful" Show instances are not compositional.

So GHC RTS tires to provide the developer with as much detailed and parsable information about unhandled exceptions as possible. Leaving the ability to use displayExceptions to tell the end user about handled exceptions.

like image 175
max taldykin Avatar answered Oct 15 '22 10:10

max taldykin