Skip to content

Commit

Permalink
Move predicate for assessing raw errors from middleware to Api.Server
Browse files Browse the repository at this point in the history
  • Loading branch information
KtorZ committed May 23, 2019
1 parent 11b42d6 commit 526eaf1
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 14 deletions.
7 changes: 6 additions & 1 deletion lib/core/src/Cardano/Wallet/Api/Server.hs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ import Data.Generics.Internal.VL.Lens
( (^.) )
import Data.Generics.Labels
()
import Data.Maybe
( isJust )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
Expand Down Expand Up @@ -447,7 +449,8 @@ instance LiftHandler ErrUpdatePassphrase where
ErrUpdatePassphraseWithRootKey e -> handler e

instance LiftHandler ServantErr where
handler err@(ServantErr code _ body headers) = case code of
handler err@(ServantErr code _ body headers)
| not (isJSON body) = case code of
400 -> apiError err' BadRequest (utf8 body)
404 -> apiError err' NotFound $ mconcat
[ "I couldn't find the requested endpoint. If the endpoint "
Expand Down Expand Up @@ -478,8 +481,10 @@ instance LiftHandler ServantErr where
, "don't yet know how to handle this type of situation. Here's "
, "some information about what happened: ", utf8 body
]
| otherwise = err
where
utf8 = T.replace "\"" "'" . T.decodeUtf8 . BL.toStrict
isJSON = isJust . Aeson.decode @Aeson.Value
err' = err
{ errHeaders =
( hContentType
Expand Down
14 changes: 1 addition & 13 deletions lib/core/src/Network/Wai/Middleware/ServantError.hs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import Control.Monad
( guard )
import Data.ByteString.Lazy
( ByteString )
import Network.HTTP.Types.Header
( ResponseHeaders )
import Network.HTTP.Types.Status
( statusCode, statusMessage )
import Network.Wai
Expand All @@ -30,7 +28,6 @@ import Servant.Server.Internal.ServantErr

import qualified Data.Binary.Builder as Binary
import qualified Data.ByteString.Char8 as B8
import qualified Network.HTTP.Types.Status as HTTP

-- | Make sure every error is converted to a suitable application-level error.
--
Expand Down Expand Up @@ -72,16 +69,7 @@ eitherRawError res =
(Right res)
(Left . flip (ServantErr code reason) headers)
in
maybeToEither $ guard (isRawError status headers) *> body

-- | Raw 'Servant' errors don't have any Content-Type. This is a lean predicate
-- but for lack of any better way of identifying them, that's a best effort.
isRawError
:: HTTP.Status
-> ResponseHeaders
-> Bool
isRawError status headers =
statusCode status >= 400 && null headers
maybeToEither $ guard (code >= 400) *> body

-- | Extract raw body of a response, only if it suitables for transformation.
-- Servant doesn't return files or streams by default, so if one of the two is
Expand Down

0 comments on commit 526eaf1

Please sign in to comment.