You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The type signature, `Handler IO Hello` shows that it's a `Handler` for
@@ -115,7 +115,9 @@ to run actions in the base monad.
115
115
116
116
The second layer of the handler, the implementation of `greeting`, produces
117
117
the value of the `greeting` field. It is monadic so that it will only be
118
-
executed when the field was requested.
118
+
executed when the field was requested. It uses the 'returns' function to
119
+
return the value for the field in the monad (technically, the Applicative
120
+
context which is OK because a Monad is Applicative).
119
121
120
122
Each field handler is a separate monadic action so we only perform the side
121
123
effects for fields present in the query.
@@ -124,6 +126,21 @@ This handler is in `Identity` because it doesn't do anything particularly
124
126
monadic. It could be in `IO` or `STM` or `ExceptT Text IO` or whatever you
125
127
would like.
126
128
129
+
### Errors in handlers
130
+
131
+
It's possible that a handler will encounter an error as well (for example, the argument might be looked up in a database and the user might specify a non-existent user). To help support GraphQL-compliant errors, a handler can use the `handlerError` function with the error text.
132
+
133
+
Here's a modified `Handler` for `Hello`:
134
+
135
+
```haskell
136
+
helloFancy :: Handler IO Hello
137
+
helloFancy = pure greeting
138
+
where
139
+
greeting who = if who == ""
140
+
then handlerError "I need to know your name!"
141
+
else returns ("Hello " <> who <> "!")
142
+
```
143
+
127
144
### Running queries
128
145
129
146
Defining a service isn't much point unless you can query. Here's how:
@@ -174,15 +191,15 @@ And its handler:
174
191
calculator :: Handler IO Calculator
175
192
calculator = pure (add :<> subtract')
176
193
where
177
-
add a b = pure (a + b)
178
-
subtract' a b = pure (a - b)
194
+
add a b = returns (a + b)
195
+
subtract' a b = returns (a - b)
179
196
```
180
197
181
198
This handler introduces a new operator, `:<>` (pronounced "birdface"), which
182
199
is used to compose two existing handlers into a new handler. It's inspired by
183
200
the operator for monoids, `<>`.
184
201
185
-
Note that we still need `pure` for each individual handler.
202
+
Note that we use `returns` for each individual handler.
186
203
187
204
## Nesting Objects
188
205
@@ -238,7 +255,7 @@ We write nested handlers the same way we write the top-level handler:
0 commit comments