Handling Errors
How to deal with errors in serverless runs
When you send a script to execute via freestyle.serverless.runs.create(), the script might contain invalid code that fails to parse, or it might encounter an error while running. The SDK throws typed errors for each case so you can handle them appropriately:
- Syntax errors occur when your script has invalid JavaScript or TypeScript that can't be parsed
- Runtime errors occur when your script executes but throws an uncaught exception
Error Types
Import the Errors namespace from the SDK to access error classes:
import { freestyle, Errors } from "freestyle-sandboxes";Syntax Errors
A SyntaxErrorError is thrown when your script contains invalid JavaScript or TypeScript syntax. The error is detected before execution begins.
try {
await freestyle.serverless.runs.create({
code: `export default () z`, // Invalid syntax
});
} catch (error) {
if (error instanceof Errors.SyntaxErrorError) {
console.log("Syntax error:", error.message);
}
}Runtime Errors
A RuntimeErrorError is thrown when your script fails during execution. This includes uncaught exceptions, failed assertions, or any error thrown by your code.
try {
await freestyle.serverless.runs.create({
code: `
export default () => {
throw new Error("Something went wrong");
}
`,
});
} catch (error) {
if (error instanceof Errors.RuntimeErrorError) {
console.log("Runtime error:", error.message);
console.log("Stack trace:", error.body.stack);
}
}Runtime errors include any logs captured before the error occurred:
try {
await freestyle.serverless.runs.create({
code: `
export default () => {
console.log("Starting...");
console.log("Processing data...");
throw new Error("Failed to process");
}
`,
});
} catch (error) {
if (error instanceof Errors.RuntimeErrorError) {
// Logs captured before the error
for (const log of error.body.logs) {
console.log(`[${log.type}] ${log.message}`);
}
}
}Error Properties
SyntaxErrorError
| Property | Type | Description |
|---|---|---|
message | string | The full error message |
body.message | string | The syntax error details |
RuntimeErrorError
| Property | Type | Description |
|---|---|---|
message | string | The full error message |
body.message | string | The runtime error details |
body.stack | string | null | Stack trace from the error |
body.logs | Array | Logs captured before the error |
Each log entry in body.logs has:
message: The log messagetype: Either"log"or"error"callstack: Optional callstack for the log