我试图在 snap 中使用 runGHC 来过滤掉可以编译的代码。但是,我正在使用 tryIO,但是当出现编译错误时,我的 webhandler 仍然会引发异常,而不是只返回一个空字符串。
import Exception (tryIO)
...
runOnFileName :: String -> IO (String)
runOnFileName inp = do
res <- sanitizeSource inp
case res of
Just (code, _, _, _) -> return $ ppr code
Nothing -> return ""
sanitizeSourceString :: String -> String -> IO (String)
sanitizeSourceString fn contents = do
tmpdir <- getTemporaryDirectory
let tmp = tmpdir </> fn ++ ".hs"
exists <- doesFileExist tmp
unless exists $ writeFile tmp $ contents
runOnFileName tmp
sanitizeSource :: String -> IO (Maybe RenamedSource)
sanitizeSource inp = do
runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
let dflags' = foldl xopt_set dflags
[Opt_Cpp, Opt_ImplicitPrelude, Opt_MagicHash]
setSessionDynFlags dflags
target <- guessTarget inp Nothing
setTargets [target]
load LoadAllTargets
modSum <- getModSummary $ mkModuleName "Main"
p <- parseModule modSum
t <- typecheckModule p
d <- desugarModule t
return $ renamedSource d
... in my handler...
eitherSan <- liftIO $ tryIO $ sanitizeSourceString (T.unpack uuid) (fromMaybe "" content)
let sanitized = case eitherSan of
Left _ -> ""
Right r -> r
但是,如果我传递无法编译的“内容”,我的处理程序将失败并显示
A web handler threw an exception. Details Parse error: naked expression at top level
或任何编译器错误。我认为tryIO
应该捕获异常。