说我有像ExitFailure
这样的例外。如何在我的处理程序中匹配ExitFailure
的不同值?
import System.Exit (ExitCode(..))
import Control.Monad.Catch as Exc
value :: Either Exc.SomeException String
value = Exc.throwM . ExitFailure $ 23
valHandler :: Exc.SomeException -> Either Exc.SomeException String
valHandler e = ??
main = print $ Exc.catch value valHandler
我知道valHandler e = someValue
可以匹配任何类型的异常,但我从未见过一个例子,它与异常类型相匹配。
我不能使用模式匹配,因为我手上有SomeException
,我不能使用等式检查,因为SomeException
没有Eq
实例?
Exception
类为此提供了一种方法:
fromException :: SomeException -> Maybe e
您可以使用它来恢复异常。
valHandler :: Exc.SomeException -> Either Exc.SomeException String
valHandler e
| Just (ExitFailure code) <- fromException e
= Right ...
| otherwise = Left e