仆人打印异常

Servant print exceptions

如何打印所有异常的描述?切换 debug/release 格式会很棒。

标准 Servant 安装仅显示 500/Something went wrong 这不是很有帮助

HTTP/1.1 500 Internal Server Error

Something went wrong

更新:

我收到以下错误报告我的第一个处理程序:

Server.hs:152:31: error:
    • No instance for (MonadCatch
                         ((:<|>) (Servant.Handler (Map.Map String String))))
        arising from a use of ‘catch’
    • In the expression:
        server `catch` (\ e -> handleExceptions (e :: SomeException))
      In an equation for ‘serverWithExceptionsHandled’:
          serverWithExceptionsHandled
            = server `catch` (\ e -> handleExceptions (e :: SomeException))

处理程序本身:

type API = "ping" :> Get '[JSON] (Map.Map String String) ...

ping :: Servant.Handler (Map.Map String String)
ping = return $ Map.fromList [("reply", "pong")] 

更新:

server :: Server API
server = ping
    :<|> signup
    :<|> singin
    :<|> account
    :<|> getSessions


serverWithExceptionsHandled = server `catch` (\e -> handleExceptions (e :: SomeException))

-- | print to console and then rethrow
handleExceptions :: (MonadIO m, MonadThrow m, Exception e) => e -> m b
handleExceptions e = do
  liftIO $ print e
  throwM e

app :: Application
app = serveWithContext api ctx serverWithExceptionsHandled
        where ctx = checkBasicAuth :. EmptyContext

所有服务器代码都在 Handler 中运行,其中有一个 MonadCatch 实例和一个 MonadThrow 实例。所以你可以像这样使用异常处理程序来扭曲你的服务器代码:

handled :: Server SomeRoute
handled = server1 `catch` (\e -> handleExceptions (e :: SomeException))

type API = SomeRoute :<|> (other routes)

combined :: Server API
combined = handled :<|> (server code for other routes)

app :: Application
app = serve @API Proxy combined

其中 handleExceptions 是您的异常处理程序,例如:

-- | print to console and then rethrow
handleExceptions e = do
  liftIO $ print e
  throwM e

更多示例:

ping' = ping `catch` (\e -> handleExceptions (e :: SomeException))

server :: Server API
server = ping'
    :<|> signup
    :<|> singin
    :<|> account
    :<|> getSessions