Browse Source

error-handling

Getty Ritter 2 years ago
parent
commit
4e4a77bba7
1 changed files with 20 additions and 4 deletions
  1. 20 4
      src/Main.hs

+ 20 - 4
src/Main.hs

@@ -2,7 +2,9 @@
 
 
 module Main where
 module Main where
 
 
+import qualified Control.Applicative as App
 import qualified Control.Exception as Exn
 import qualified Control.Exception as Exn
+import qualified Control.Monad as Monad
 import qualified Foreign.Lua as Lua
 import qualified Foreign.Lua as Lua
 
 
 data Config = Config
 data Config = Config
@@ -12,6 +14,16 @@ data Config = Config
   }
   }
   deriving (Show)
   deriving (Show)
 
 
+-- a very barebones attempt at doing error conversion: we ignore a
+-- bunch of stuff, but we do translate Lua errors into Haskell errors
+errorConversion :: Lua.ErrorConversion
+errorConversion = Lua.ErrorConversion {Lua.errorToException, Lua.addContextToException, Lua.alternative, Lua.exceptionToError}
+  where
+    errorToException = Lua.throwTopMessageWithState
+    addContextToException _ x = x
+    alternative x y = x App.<|> y
+    exceptionToError = id
+
 readConfig :: FilePath -> IO Config
 readConfig :: FilePath -> IO Config
 readConfig configPath =
 readConfig configPath =
   -- set up a new Lua state, and make sure we close it at the end
   -- set up a new Lua state, and make sure we close it at the end
@@ -19,14 +31,18 @@ readConfig configPath =
     -- we should set up a mechanism to convert Lua/Haskell errors into
     -- we should set up a mechanism to convert Lua/Haskell errors into
     -- one another, but that seems like a lot of work here, so this
     -- one another, but that seems like a lot of work here, so this
     -- just panics whenever any errors happen, hence `unsafeRunWith`
     -- just panics whenever any errors happen, hence `unsafeRunWith`
-    Lua.unsafeRunWith st $ do
+    Lua.runWithConverter errorConversion st $ do
       -- this loads the stdlib into Lua, but you probably don't
       -- this loads the stdlib into Lua, but you probably don't
       -- actually want this in a config file! (it allows e.g. file IO
       -- actually want this in a config file! (it allows e.g. file IO
       -- and stuff)
       -- and stuff)
       Lua.openlibs
       Lua.openlibs
-      -- load the actual config path. this should check error
-      -- conditions, but eh.
-      _ <- Lua.loadfile configPath
+      -- load the actual config path
+      res <- Lua.loadfile configPath
+      -- if that didn't work, then take the Lua error and turn it into
+      -- a Haskell exception
+      Monad.when
+        (res /= Lua.OK)
+        Lua.throwErrorAsException
       -- that simply loads the code as a zero-argument function: now
       -- that simply loads the code as a zero-argument function: now
       -- call it
       -- call it
       Lua.call 0 0
       Lua.call 0 0