Skip to content

Commit bb2c6e5

Browse files
committed
include content updates
1 parent 7968a54 commit bb2c6e5

File tree

4 files changed

+100
-94
lines changed

4 files changed

+100
-94
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
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:
4+
5+
```js
6+
const TOKEN_EXPIRE_MS = 60 * 60 * 1000 // 1 hour
7+
let token = null
8+
async function getAccessToken () {
9+
const now = new Date().getTime()
10+
if (!token || now - token.ts > TOKEN_EXPIRE_MS) {
11+
const resp = await fetch('https://example.com/tokens', {
12+
method: 'POST'
13+
}).then(resp => resp.json())
14+
token = {
15+
ts: now,
16+
value: resp.token
17+
}
18+
}
19+
return token.value
20+
}
21+
```
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<!-- Use for destination and insert functions -->
2+
3+
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+
async function onGroup(event) {
16+
if (!event.traits.company) {
17+
throw new InvalidEventPayload('Company name is required')
18+
}
19+
}
20+
21+
async function onPage(event) {
22+
if (!event.properties.pageName) {
23+
throw new ValidationError('Page name is required')
24+
}
25+
}
26+
27+
async function onAlias(event) {
28+
throw new EventNotSupported('Alias event is not supported')
29+
}
30+
31+
async function onTrack(event) {
32+
let res
33+
try {
34+
res = await fetch('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+
throw new RetryError(err.message)
44+
}
45+
if (res.status >= 500 || res.status === 429) {
46+
// Retry on 5xx and 429s (ratelimits)
47+
throw new RetryError(`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.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
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:
6+
7+
```js
8+
async function onTrack(event, settings) {
9+
const userId = event.userId
10+
11+
console.log('User ID is', userId)
12+
13+
if (typeof userId !== 'string' || userId.length < 8) {
14+
throw new ValidationError('User ID is invalid')
15+
}
16+
17+
console.log('User ID is valid')
18+
}
19+
```
20+

src/connections/functions/insert-functions.md

Lines changed: 5 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ To create an insert function from Segment's catalog:
3030

3131
1. Navigate to **Connections > Catalog > Functions** and click **Create function**.
3232
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.
3434
4. Click **Next: Configure and Deploy** to add a function name, description, and logo.
3535
5. Click **Create function** to create your insert function. You'll see the function displayed in the Insert functions tab.
3636

@@ -96,58 +96,7 @@ To change which event type the handler listens to, you can rename it to the name
9696
9797
### Errors and error handling
9898

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-
async function onGroup(event) {
112-
if (!event.traits.company) {
113-
throw new InvalidEventPayload('Company name is required')
114-
}
115-
}
116-
117-
async function onPage(event) {
118-
if (!event.properties.pageName) {
119-
throw new ValidationError('Page name is required')
120-
}
121-
}
122-
123-
async function onAlias(event) {
124-
throw new EventNotSupported('Alias event is not supported')
125-
}
126-
127-
async function onTrack(event) {
128-
let res
129-
try {
130-
res = await fetch('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-
throw new RetryError(err.message)
140-
}
141-
if (res.status >= 500 || res.status === 429) {
142-
// Retry on 5xx and 429s (ratelimits)
143-
throw new RetryError(`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 %}
151100

152101
## Create settings and secrets
153102

@@ -238,58 +187,20 @@ A function can throw errors, or Segment might encounter errors while invoking yo
238187
- **Unsupported Event Type** - Your code doesn't implement a specific event type (for example, `onTrack()`) or threw an `EventNotSupported` error.
239188
- **Retry** - Your code threw `RetryError` indicating that the function should be retried.
240189

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.
242191

243192
You can view Segment's list of [Integration Error Codes](/docs/connections/integration_error_codes/) for more information about what might cause an error.
244193

245194
### Destination insert functions logs
246195

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-
async function onTrack(event, settings) {
255-
const userId = event.userId
256-
257-
console.log('User ID is', userId)
258-
259-
if (typeof userId !== 'string' || userId.length < 8) {
260-
throw new ValidationError('User ID is invalid')
261-
}
262-
263-
console.log('User ID is valid')
264-
}
265-
```
196+
{% include content/functions/logs.md %}
266197

267198
> warning ""
268199
> 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.
269200
270201
## Caching in destination insert functions
271202

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:
275-
276-
```js
277-
const TOKEN_EXPIRE_MS = 60 * 60 * 1000 // 1 hour
278-
let token = null
279-
async function getAccessToken () {
280-
const now = new Date().getTime()
281-
if (!token || now - token.ts > TOKEN_EXPIRE_MS) {
282-
const resp = await fetch('https://example.com/tokens', {
283-
method: 'POST'
284-
}).then(resp => resp.json())
285-
token = {
286-
ts: now,
287-
value: resp.token
288-
}
289-
}
290-
return token.value
291-
}
292-
```
203+
{% include content/functions/caching.md %}
293204

294205
## Managing destination insert functions
295206

0 commit comments

Comments
 (0)