magicbane icon indicating copy to clipboard operation
magicbane copied to clipboard

Exception Handling

Open jeremyjh opened this issue 5 years ago • 2 comments

In my application, I would like for the Wai Logger middleware to write a message to the log when an unhandled exception occurs and 500 response is sent to the client. For this to happen, it looks we need to catch that exception and respond inside our Application. A basic example of how this would be done in servant is

app :: Application
app = serve api $ hoistServer api nt server

nt :: Handler a -> Handler a
nt = handleAny throwEx
    where
      throwEx e = throwError $ err500 {errBody = "The following server exception occured: " <> (cs $ show e)}

How can I do the same thing using magicbaneApp ? Or is this something magicbane could do?

jeremyjh avatar Sep 21 '18 10:09 jeremyjh

Right now, you can write your own magicbaneApp to compose your nt with runMagicbaneHandler c. I'll look into adding an argument to remove the need for duplicating the function :)

valpackett avatar Sep 21 '18 11:09 valpackett

Thanks, I think it would be great if Magicbane had options for this. If it wired up request logging out of the box that would be great too. I ended up writing a small middleware for now:

exceptionResponder :: AppContext -> Middleware
exceptionResponder ctx next request respond =
    next request respond `catch` \(exception :: SomeException) -> do
        runRIO ctx $ logError $ "Unhandled exception: " <> display exception
        respond $
            responseLBS
                status500
                [("Content-Type", "application/json")]
                "{\"message\": \"An error has occurred.\"}"

jeremyjh avatar Sep 22 '18 01:09 jeremyjh