0 | module HTTP.RequestErr
 1 |
 2 | import Control.Monad.MErr
 3 | import Data.Either
 4 | import Derive.Prelude
 5 | import HTTP.Status
 6 | import JSON.Simple
 7 | import JSON.Simple.Derive
 8 |
 9 | %default total
10 | %language ElabReflection
11 |
12 | public export
13 | record RequestErr where
14 |   constructor RE
15 |   status  : Bits16
16 |   error   : String
17 |   message : String
18 |   details : Either JSON String
19 |   path    : String
20 |
21 | %runElab derive "RequestErr" [Show,Eq,FromJSON,ToJSON]
22 |
23 | export
24 | requestErr : Status -> RequestErr
25 | requestErr (MkStatus c e) = RE c e "" (Left JNull) ""
26 |
27 | export
28 | requestErrMsg : String -> Status -> RequestErr
29 | requestErrMsg m (MkStatus c e) = RE c e m (Left JNull) ""
30 |
31 | export
32 | requestErrDetails : Interpolation a => a -> Status -> RequestErr
33 | requestErrDetails v (MkStatus c e) = RE c e "" (Right "\{v}") ""
34 |
35 | export
36 | requestErrJSON : ToJSON a => a -> Status -> RequestErr
37 | requestErrJSON v (MkStatus c e) = RE c e "" (Left $ toJSON v) ""
38 |
39 | ||| Tries to convert a `RequestErr` to an error of type `e`
40 | ||| by decoding its `details` field.
41 | export
42 | toJSONErr : FromJSON e => RequestErr -> Maybe e
43 | toJSONErr (RE _ _ _ (Left j)  _) = eitherToMaybe $ fromJSON j
44 | toJSONErr (RE _ _ _ (Right s) _) = eitherToMaybe $ decode s
45 |
46 | ||| Tries to convert a `RequestErr` to an error of type `e`
47 | ||| and throws that in case the conversion succeeds. Otherwise,
48 | ||| the original request error is rethrown.
49 | export
50 | decodeErr :
51 |      (0 e : Type)
52 |   -> {auto hr : Has RequestErr es}
53 |   -> {auto ha : Has e es}
54 |   -> {auto fj : FromJSON e}
55 |   -> {auto me : MErr f}
56 |   -> f es a
57 |   -> f es a
58 | decodeErr e act =
59 |   catch RequestErr act >>= \case
60 |     Right v => pure v
61 |     Left x  => maybe (throw x) throw (toJSONErr @{fj} x)
62 |