理想情况下,我会将您的功能重构为
unify' :: [Constraint] -> Maybe [Substitution]
unify' = -- your original function, but return Nothing instead of calling error,
-- and return Just x when your original function would return x
unify = fromMaybe (error "Circular constraint") . unify'
然后我会 testunify'
而不是 testing unify
。
如果有不止一个可能的错误消息,我会改成这样重构它:
unify' :: [Constraint] -> Either String [Substitution]
-- and return Left foo instead of calling error foo
unify = either error id . unify'
(顺便说一句,如果这是其他程序员将使用的库,他们中的一些人更愿意调用unify'
而不是偏函数unify
。)
如果你不能重构你的代码,我会修改你链接到的代码,替换assertException
为:
assertErrorCall :: String -> IO a -> IO ()
assertErrorCall desiredErrorMessage action
= handleJust isWanted (const $ return ()) $ do
action
assertFailure $ "Expected exception: " ++ desiredErrorMessage
where isWanted (ErrorCall actualErrorMessage)
= guard $ actualErrorMessage == desiredErrorMessage