我想一個簡單的處理程序添加到readFile
功能:異常處理「READFILE」
readHandler :: IOError -> IO()
readHandler e
| isDoesNotExistError e = putStrLn "The file does not exist"
| otherwise = putStrLn "Something went wrong"
main = do
// stop executing if there is no file
contents <- (readFile "path.xml") `catch` readHandler
// generates [(x,y),(x,y)]
coordinates = parseXML contents
// I want to do something with the coordinates
nextFunction coordinates
當我嘗試編譯此我得到的錯誤:
Couldn't match type `()' with `[Char]'
Expected type: IOError -> IO String
Actual type: IOError -> IO()
In the second argument of `catch', namely `readHandler'
In a stmt of a 'do' block:
contents <- (readFile "path") `catch` readHandler
In the expression:
do { contents <- (readFile "path") `catch` readHandler;
putStrLn contents }
因此readHandler :: IOError -> IO()
應該是readHandler :: IOError -> IO String
。
但是這樣我就不能打印錯誤信息。
我應該如何解決這個問題?
我編輯我的代碼更清晰。有沒有辦法與我的處理程序一起使用第二個解決方案,如果找到該文件,繼續執行我的執行鏈? –
@格特 - 揚肯定,而不是隻打印字符串,把任何你打算在這種情況下,分公司使用的字符串。這當然是醜陋的。一種不合理的方法是「單一」單元。 – jozefg
現在的問題是,「strOrExc」的類型爲「無論是A0字符串」,而不是‘字符串’。我認爲我對Haskell的知識還不足以解決這個問題。謝謝你的幫助! :) –