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
Functions execute only in response to incoming data, but the environments that functions run in are generally long-running. Because of this, you can use global variables to cache small amounts of information between invocations. For example, you can reduce the number of access tokens you generate by caching a token, and regenerating it only after it expires. Segment cannot make any guarantees about the longevity of environments, but by using this strategy, you can improve the performance and reliability of your Functions by reducing the need for redundant API requests.
2
+
3
+
This example code fetches an access token from an external API and refreshes it every hour:
Segment considers a function's execution successful if it finishes without error. You can also `throw` an error to create a failure on purpose. Use these errors to validate event data before processing it, to ensure the function works as expected.
4
+
5
+
You can `throw` the following pre-defined error types to indicate that the function ran as expected, but that data was deliverable:
6
+
7
+
-`EventNotSupported`
8
+
-`InvalidEventPayload`
9
+
-`ValidationError`
10
+
-`RetryError`
11
+
12
+
The examples show basic uses of these error types.
13
+
14
+
```js
15
+
asyncfunctiononGroup(event) {
16
+
if (!event.traits.company) {
17
+
thrownewInvalidEventPayload('Company name is required')
18
+
}
19
+
}
20
+
21
+
asyncfunctiononPage(event) {
22
+
if (!event.properties.pageName) {
23
+
thrownewValidationError('Page name is required')
24
+
}
25
+
}
26
+
27
+
asyncfunctiononAlias(event) {
28
+
thrownewEventNotSupported('Alias event is not supported')
29
+
}
30
+
31
+
asyncfunctiononTrack(event) {
32
+
let res
33
+
try {
34
+
res =awaitfetch('http://example-service.com/api', {
35
+
method:'POST',
36
+
headers: {
37
+
'Content-Type':'application/json'
38
+
},
39
+
body:JSON.stringify({ event })
40
+
})
41
+
} catch (err) {
42
+
// Retry on connection error
43
+
thrownewRetryError(err.message)
44
+
}
45
+
if (res.status>=500||res.status===429) {
46
+
// Retry on 5xx and 429s (ratelimits)
47
+
thrownewRetryError(`HTTP Status ${res.status}`)
48
+
}
49
+
}
50
+
51
+
```
52
+
If you don't supply a function for an event type, Segment throws an `EventNotSupported` error by default.
53
+
54
+
You can read more about [error handling](#destination-functions-logs-and-errors) below.
If your function throws an error, execution halts immediately. Segment captures the event, any outgoing requests/responses, any logs the function might have printed, as well as the error itself.
2
+
3
+
Segment then displays the captured error information in the [Event Delivery](/docs/connections/event-delivery/) page for your function. You can use this information to find and fix unexpected errors.
4
+
5
+
You can throw [an error or a custom error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error){:target="_blank"} and you can also add helpful context in logs using the [`console` API](https://developer.mozilla.org/en-US/docs/Web/API/console){:target="_blank"}. For example:
Copy file name to clipboardExpand all lines: src/connections/functions/insert-functions.md
+5-94Lines changed: 5 additions & 94 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -30,7 +30,7 @@ To create an insert function from Segment's catalog:
30
30
31
31
1. Navigate to **Connections > Catalog > Functions** and click **Create function**.
32
32
2. From the Select Type screen, select **Insert Functions** and click **Next: Build function**.
33
-
3. Write your function code, then click **Use Sample Event** to test it. Create a sample event, then click **Run** to test.
33
+
3. Write your function code, and test it. Manually enter a sample event, then click **Run** to test.
34
34
4. Click **Next: Configure and Deploy** to add a function name, description, and logo.
35
35
5. Click **Create function** to create your insert function. You'll see the function displayed in the Insert functions tab.
36
36
@@ -96,58 +96,7 @@ To change which event type the handler listens to, you can rename it to the name
96
96
97
97
### Errors and error handling
98
98
99
-
Segment considers a function's execution successful if it finishes without error. You can also `throw` an error to create a failure on purpose. Use these errors to validate event data before processing it, to ensure the function works as expected.
100
-
101
-
You can `throw` the following pre-defined error types to indicate that the function ran as expected, but that data was deliverable:
102
-
103
-
-`EventNotSupported`
104
-
-`InvalidEventPayload`
105
-
-`ValidationError`
106
-
-`RetryError`
107
-
108
-
The examples show basic uses of these error types.
109
-
110
-
```js
111
-
asyncfunctiononGroup(event) {
112
-
if (!event.traits.company) {
113
-
thrownewInvalidEventPayload('Company name is required')
114
-
}
115
-
}
116
-
117
-
asyncfunctiononPage(event) {
118
-
if (!event.properties.pageName) {
119
-
thrownewValidationError('Page name is required')
120
-
}
121
-
}
122
-
123
-
asyncfunctiononAlias(event) {
124
-
thrownewEventNotSupported('Alias event is not supported')
125
-
}
126
-
127
-
asyncfunctiononTrack(event) {
128
-
let res
129
-
try {
130
-
res =awaitfetch('http://example-service.com/api', {
131
-
method:'POST',
132
-
headers: {
133
-
'Content-Type':'application/json'
134
-
},
135
-
body:JSON.stringify({ event })
136
-
})
137
-
} catch (err) {
138
-
// Retry on connection error
139
-
thrownewRetryError(err.message)
140
-
}
141
-
if (res.status>=500||res.status===429) {
142
-
// Retry on 5xx and 429s (ratelimits)
143
-
thrownewRetryError(`HTTP Status ${res.status}`)
144
-
}
145
-
}
146
-
147
-
```
148
-
If you don't supply a function for an event type, Segment throws an `EventNotSupported` error by default.
149
-
150
-
You can read more about [error handling](#destination-functions-logs-and-errors) below.
99
+
{% include content/functions/errors-and-error-handling.md %}
151
100
152
101
## Create settings and secrets
153
102
@@ -238,58 +187,20 @@ A function can throw errors, or Segment might encounter errors while invoking yo
238
187
-**Unsupported Event Type** - Your code doesn't implement a specific event type (for example, `onTrack()`) or threw an `EventNotSupported` error.
239
188
-**Retry** - Your code threw `RetryError` indicating that the function should be retried.
240
189
241
-
Segment only attempts to send the event to your destination function again if a **Retry** error occurs.
190
+
Segment only attempts to send the event to your destination insert function again if a **Retry** error occurs.
242
191
243
192
You can view Segment's list of [Integration Error Codes](/docs/connections/integration_error_codes/) for more information about what might cause an error.
244
193
245
194
### Destination insert functions logs
246
195
247
-
If your function throws an error, execution halts immediately. Segment captures the event, any outgoing requests/responses, any logs the function might have printed, as well as the error itself.
248
-
249
-
Segment then displays the captured error information in the [Event Delivery](/docs/connections/event-delivery/) page for your destination insert function. You can use this information to find and fix unexpected errors.
250
-
251
-
You can throw [an error or a custom error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error){:target="_blank"} and you can also add helpful context in logs using the [`console` API](https://developer.mozilla.org/en-US/docs/Web/API/console){:target="_blank"}. For example:
252
-
253
-
```js
254
-
asyncfunctiononTrack(event, settings) {
255
-
constuserId=event.userId
256
-
257
-
console.log('User ID is', userId)
258
-
259
-
if (typeof userId !=='string'||userId.length<8) {
260
-
thrownewValidationError('User ID is invalid')
261
-
}
262
-
263
-
console.log('User ID is valid')
264
-
}
265
-
```
196
+
{% include content/functions/logs.md %}
266
197
267
198
> warning ""
268
199
> Don't log sensitive data, such as personally-identifying information (PII), authentication tokens, or other secrets. Avoid logging entire request/response payloads. The **Function Logs** tab may be visible to other workspace members if they have the necessary permissions.
269
200
270
201
## Caching in destination insert functions
271
202
272
-
Functions execute only in response to incoming data, but the environments that functions run in are generally long-running. Because of this, you can use global variables to cache small amounts of information between invocations. For example, you can reduce the number of access tokens you generate by caching a token, and regenerating it only after it expires. Segment cannot make any guarantees about the longevity of environments, but by using this strategy, you can improve the performance and reliability of your Functions by reducing the need for redundant API requests.
273
-
274
-
This example code fetches an access token from an external API and refreshes it every hour:
0 commit comments