Error handling

Updated at:

Function Compute catches errors thrown by your Node.js function and returns a structured response. This page covers the two error categories Node.js functions can produce and how to interpret HTTP status codes from the service.

Error types

Captured exceptions

When your function throws an exception, Function Compute catches it and returns a JSON object with three fields:

Field Description
errorMessage The error message string
errorType The JavaScript error class name
stackTrace An array of stack frames

ECMAScript modules

ECMAScript module syntax requires Node.js 18 or later. The sample code supports one-click deployment (nodejs-fc-err-es).
export const handler = async (event, context) => {
  throw new Error('oops');
};

CommonJS modules

exports.handler = function(event, context, callback) {
  throw new Error('oops');
};

Sample response:

{
    "errorMessage": "oops",
    "errorType": "Error",
    "stackTrace": [
        "Error: oops",
        "    at handler (file:///code/index.mjs:2:9)",
        "    at module.exports (file:///var/fc/runtime/nodejs20/bootstrap.mjs:5655:14)",
        "    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"
    ]
}

Abnormal exits

If your function calls process.exit() while running, the runtime cannot capture a structured error. The service returns a generic message instead:

ECMAScript modules

ECMAScript module syntax requires Node.js 18 or later.
export const handler = async (event, context) => {
  process.exit(1);
};

CommonJS modules

exports.handler = function(event, context, callback) {
  process.exit(1);
};

Sample response:

{
    "errorMessage": "Process exited unexpectedly before completing request (duration: 12ms, maxMemoryUsage: 0MB)"
}

HTTP status codes

Important

A 2xx response does not guarantee the function succeeded. Check for the X-Fc-Error-Type response header to detect function errors returned with a 2xx status code.

When a function invocation fails, Function Compute returns an HTTP status code, a response body, and — for function-level errors — an X-Fc-Error-Type response header. Inspect these signals to handle errors in code or surface them to end users.

Status code Meaning
2xx Function Compute received the request. If the response includes the X-Fc-Error-Type header, a function error occurred — for example, an uncaught exception in your code.
4xx (excluding 429) The client that initiated the invocation sent an invalid request.
429 The request was throttled.
5xx An internal error occurred in Function Compute, the function configuration is invalid, or a resource issue exists.

For more information about invocation errors, see Configure a retry mechanism.

FAQ

require is not defined in ES module scope

Symptom

When the entry file of a Node.js function is loaded as an ES module (the file extension is .mjs, or package.json sets "type": "module") and the code uses require() to load modules, the invocation returns HTTP status code 200, the response headers include X-Fc-Error-Type: InvocationError, and the response body contains the following error:

{
    "errorMessage": "require is not defined in ES module scope, you can use import instead",
    "errorType": "ReferenceError",
    "stackTrace": [
        "ReferenceError: require is not defined in ES module scope, you can use import instead",
        "    at file:///code/index.mjs:1:15",
        "    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)"
    ]
}

The error content varies depending on the entry file type and the location of require():

  • If the entry file has a .js extension and package.json sets "type": "module", errorMessage includes an additional line: This file is being treated as an ES module because it has a '.js' file extension and '/code/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

  • If require() is called inside the handler function rather than at the top level of the module, errorMessage is require is not defined.

Cause

require() is the loading function of the CommonJS module system and is unavailable in ES module scope. After a file is identified as an ES module, Node.js does not inject CommonJS variables such as require, module, and exports.

Solution

Choose one of the following methods based on your code structure:

  • Rewrite require() as ES module import statements. To load a module dynamically, use the import() expression.

  • To keep the require() syntax, rename the entry file extension to .cjs. No change to the function handler configuration is required.

The following example shows the ES module rewrite (entry file index.mjs):

// Import a Node.js built-in module and a local ES module file
import { createHash } from 'node:crypto';
import { helper } from './utils.mjs';

export const handler = async (event, context) => {
  return createHash('sha256').update(helper()).digest('hex');
};

The following example shows how to dynamically load a module:

const crypto = await import('node:crypto');

The following example shows the CommonJS syntax (entry file index.cjs):

const crypto = require('crypto');

exports.handler = async (event, context) => {
  return crypto.createHash('sha256').digest('hex');
};
Note: To load a third-party dependency (such as lodash), run npm install locally first, and then package and deploy the node_modules directory together with your code. In ES modules, you can reference a CommonJS dependency by using a default import, for example, import _ from 'lodash';.

ES modules are supported only in Node.js 18 and later runtimes. In Node.js 16 and earlier runtimes, an .mjs entry file is not loaded, and the invocation returns "errorMessage": "Module '/code/index.js' is missing." and "errorType": "FunctionUnhandledError: ImportModuleError".