Skip to main content

Handle errors in app functions

In case something isn't working as expected in your app function, you want to react accordingly on the function consumer's side. This guide describes how to handle errors in your function code and report them back to the consumer.

Return error code

By default, app functions return HTTP status code 200 if there's no error thrown. If something unexpected happens in your function code, you can throw an error anytime, leading to an HTTP 540 status code returned by the app function.

This could look like this in case a call to a 3rd party API is failing in your function:

api/fetch-people.ts
export default async function () {
const apiResponse = await fetch('https://swapi.dev/api/people/1/');
if (!apiResponse.ok) {
throw new Error();
}

return apiResponse.json();
}
Caution

Throwing an error in your app function leads to a generic Execution crashed error message. You can't create a custom error with this approach. If you want to report custom errors read the next section.

Custom error reporting

If you want to report a different kind of error information back to your consumer based on the type of error you are facing, you can also include all kinds of error information in your return object.

The following example demonstrates how you could return a different response object with error information from the external API.

api/fetch-people-custom-error-reporting.ts
interface Result {
data: any;
error?: string;
}

export default async function (): Promise<Result> {
const apiResponse = await fetch('https://swapi.dev/api/people/1/');
if (!apiResponse.ok) {
const responseText = await apiResponse.text();
return {
data: null,
error: 'External API failed to handle the request: ' + responseText,
};
}

const data = await apiResponse.json();
return {
data,
};
}
Still have questions?
Find answers in the Dynatrace Community