如何包装异常以提供上下文?

时间:2014-12-07 18:43:26

标签: haskell

假设我有一个下载文件并尝试解析它的函数。无论使用的任何低级函数引发了什么异常,我都希望通过添加url来丰富它的上下文信息。

1 个答案:

答案 0 :(得分:2)

它是possible to catch all exceptions, though not recommended。然后,您可以使用URL标记例外并重新加载它:

{-# LANGUAGE DeriveDataTypeable #-}                                                                         
module Temp where                                                                                           

import Control.Exception                                                                                    
import Data.Typeable                                                                                        

type URL = String                                                                                           
data URLTaggedException e = URLTaggedException { baseException :: e, url :: URL } deriving (Typeable, Show) 
instance (Typeable e, Show e) => Exception (URLTaggedException e)                                           

tagExceptionsWithURL :: URL -> IO a -> IO a                                                                 
tagExceptionsWithURL url io = catch io (throwIO . tag)                                                      
  where tag :: SomeException -> URLTaggedException SomeException                                            
        tag e = URLTaggedException e url