在Haskell中,与Java的e.printStackTrace等效的方法是什么?

3
我正在尝试使用Haskell的Kafka库,从git中获取并出现了error。为了调试此错误,我想在错误行打印堆栈跟踪。
在Python世界中,只需这样做:
import traceback; print traceback.print_exc()

(或者)在Java中,它是

e.printStackTrace()

那么,如何在Haskell世界中实现相同的功能呢?


1
调试方面的维基页面可能会为您提供答案:https://wiki.haskell.org/Debugging - Taylor Fausak
2
Haskell的错误通常都很明确。我从来没有遇到过一个无法仅凭错误信息解决的Haskell错误。实际上,错误信息表明给定了一个“Left something”的值,因此必须失败。我已经在github上发布了我的回复。 - AJF
1个回答

3
您可以在Haskell中获取堆栈跟踪,但它不像e.printStackTrace()那样方便。以下是一个最小的示例:
import Control.Exception
import Debug.Trace

getStack :: String -> SomeException -> IO a
getStack msg e = traceStack (show e) $ error msg

main :: IO ()
main = do
    (head []) `catch` (getStack "error on main at head")

最后,使用ghc -prof -fprof-auto StackTrace.hs编译它,会生成:
Prelude.head: empty list              
Stack trace:                          
  Main.getStack (StackTrace.hs:5:9-56)     
  Main.main (StackTrace.hs:(8,9)-(9,74))   
  GHC.List.CAF (<entire-module>)      
StackTrace.exe: error on main at head

Arbus,你是怎么运行这个的?我用的是 runhaskell file.hs 命令,它打印出了 Prelude.head: empty list st.hs: error on main at head ... 你是使用 ghc 还是 runhaskell? - user2879704
啊,抱歉,我忘了提到你需要这样编译:ghc -prof -fprof-auto StackTrace.hs,现在已经编辑答案了。 - Arbus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接