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 not 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.
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/destination-functions.md
+2-87Lines changed: 2 additions & 87 deletions
Original file line number
Diff line number
Diff line change
@@ -81,56 +81,7 @@ To change which event type the handler listens to, you can rename it to the name
81
81
82
82
### Errors and error handling
83
83
84
-
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.
85
-
86
-
You can `throw` the following pre-defined error types to indicate that the function ran as expected, but that data was deliverable:
87
-
88
-
-`EventNotSupported`
89
-
-`InvalidEventPayload`
90
-
-`ValidationError`
91
-
-`RetryError`
92
-
93
-
The examples show basic uses of these error types.
94
-
95
-
```js
96
-
asyncfunctiononGroup(event) {
97
-
if (!event.traits.company) {
98
-
thrownewInvalidEventPayload('Company name is required')
99
-
}
100
-
}
101
-
102
-
asyncfunctiononPage(event) {
103
-
if (!event.properties.pageName) {
104
-
thrownewValidationError('Page name is required')
105
-
}
106
-
}
107
-
108
-
asyncfunctiononAlias(event) {
109
-
thrownewEventNotSupported('Alias event is not supported')
110
-
}
111
-
112
-
asyncfunctiononTrack(event) {
113
-
let res
114
-
try {
115
-
res =awaitfetch('http://example-service.com/api', {
116
-
method:'POST',
117
-
headers: {
118
-
'Content-Type':'application/json'
119
-
},
120
-
body:JSON.stringify({ event })
121
-
})
122
-
} catch (err) {
123
-
// Retry on connection error
124
-
thrownewRetryError(err.message)
125
-
}
126
-
if (res.status>=500||res.status===429) {
127
-
// Retry on 5xx and 429s (ratelimits)
128
-
thrownewRetryError(`HTTP Status ${res.status}`)
129
-
}
130
-
}
131
-
132
-
```
133
-
If you don't supply a function for an event type, Segment throws an `EventNotSupported` error by default.
84
+
{% include content/functions/errors-and-error-handling.md %}
134
85
135
86
You can read more about [error handling](#destination-functions-logs-and-errors) below.
136
87
@@ -379,43 +330,7 @@ You can also choose to **Save & Deploy** to save the changes, and then choose wh
379
330
380
331
## Destination functions logs and errors
381
332
382
-
A function can throw errors, or Segment might encounter errors while invoking your function. You can view these errors in the [Event Delivery](/docs/connections/event-delivery/) tab for your Destination as in the example below.
383
-
384
-

385
-
386
-
### Destination functions error types
387
-
388
-
-**Bad Request** - Any error thrown by the function code that is not covered by the other errors.
389
-
-**Invalid Settings** - A configuration error prevented Segment from executing your code. If this error persists for more than an hour, [contact Segment Support](https://segment.com/help/contact/){:target="_blank"}.
390
-
-**Message Rejected** - Your code threw `InvalidEventPayload` or `ValidationError` due to invalid input.
391
-
-**Unsupported Event Type** - Your code doesn't implement a specific event type (for example, `onTrack()`) or threw an `EventNotSupported` error.
392
-
-**Retry** - Your code threw `RetryError` indicating that the function should be retried.
393
-
394
-
Segment only attempts to send the event to your destination function again if a **Retry** error occurs.
395
-
396
-
You can view Segment's list of [Integration Error Codes](/docs/connections/integration_error_codes/) for more information about what might cause an error.
397
-
398
-
### Destination functions logs
399
-
400
-
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.
401
-
402
-
Segment then displays the captured error information in the [Event Delivery](/docs/connections/event-delivery/) page for your destination function. You can use this information to find and fix unexpected errors.
403
-
404
-
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:
405
-
406
-
```js
407
-
asyncfunctiononTrack(event, settings) {
408
-
constuserId=event.userId
409
-
410
-
console.log('User ID is', userId)
411
-
412
-
if (typeof userId !=='string'||userId.length<8) {
413
-
thrownewValidationError('User ID is invalid')
414
-
}
415
-
416
-
console.log('User ID is valid')
417
-
}
418
-
```
333
+
{% include content/functions/logs.md %}
419
334
420
335
> warning ""
421
336
> **Warning:** Do not 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.
Copy file name to clipboardExpand all lines: src/connections/functions/environment.md
+1-1Lines changed: 1 addition & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -16,7 +16,7 @@ When you create a function, write code for it, and save it, the function appears
16
16
Only [Functions admins](#functions-permissions) can create or edit functions.
17
17
18
18
1. From your workspace, go to the Catalog and click the [Functions tab](https://app.segment.com/goto-my-workspace/functions/catalog){:target="_blank"}.
19
-
2. Click **New Function**.
19
+
2. Click **Create function**.
20
20
3. Select the type of function you want to build, and click **Build**.
21
21
22
22
When you click **Build**, a code editor appears. Different template code is available depending on which type of function you created.
Copy file name to clipboardExpand all lines: src/connections/functions/index.md
+14-1Lines changed: 14 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -10,7 +10,7 @@ Functions let you create your own sources and destinations directly within your
10
10

11
11
12
12
## What can you do with Functions?
13
-
Functions can help you bring external data into Segment ([Source functions](/docs/connections/functions/source-functions)) and send data in Segment out to external destinations ([Destination functions](/docs/connections/functions/destination-functions)). Functions are scoped to your specific workspace. If you're a technology partner and want to build a new integration and publish it in Segment's catalog, see the [Developer Center documentation](/docs/partners/).
13
+
Functions can help you bring external data into Segment ([Source functions](/docs/connections/functions/source-functions)) and send data in Segment out to external destinations ([Destination functions](/docs/connections/functions/destination-functions)). Use [Insert functions](/docs/connections/functions/insert-functions) to transform data before it reaches your downstream destinations. Functions are scoped to your specific workspace. If you're a technology partner and want to build a new integration and publish it in Segment's catalog, see the [Developer Center documentation](/docs/partners/).
14
14
15
15
#### Source functions
16
16
Source functions receive external data from a webhook and can create Segment events, objects, or both. Source functions have access to the full power of JavaScript so you can validate and transform the incoming data and even make external API requests to annotate your data.
@@ -31,3 +31,16 @@ Use cases:
31
31
- Enrich outgoing data using external APIs
32
32
33
33
Learn more about [destination functions](/docs/connections/functions/destination-functions).
34
+
35
+
#### Destination insert functions
36
+
Destination insert functions help you enrich your data with code before you send it to downstream destinations.
37
+
38
+
> info "Destination Insert Functions in Private Beta"
39
+
> Destination Insert Functions is in Private Beta, and Segment is actively working on this feature. Some functionality may change before it becomes generally available. [Contact Segment](https://segment.com/help/contact/){:target="_blank"} with any feedback or questions.
40
+
41
+
Use cases:
42
+
- Implement custom logic and enrich data with third party sources
43
+
- Transform outgoing data with advanced filtration and computation
44
+
- Ensure data compliance by performing tokenisation, encryption, or decryption before sending data downstream
45
+
46
+
To learn more, visit [destination insert functions](/docs/connections/functions/insert-functions).
0 commit comments