Error handling

更新时间:
复制 MD 格式

When a function fails, the response you receive depends on how the error occurred. Function Compute captures unhandled exceptions and returns a structured JSON error response. However, some exit patterns—such as calling System.Environment.Exit()—bypass this capture, leaving you with a minimal error message and no stack trace.

This topic explains how Function Compute handles errors in the C# runtime and how to get the most diagnostic information from failures.

How errors are returned

Errors in a C# function typically originate from one of the following sources:

  • Unhandled exceptions — exceptions thrown by your function code that are not caught before the handler returns

  • Active process exit — calling System.Environment.Exit() inside the handler, which terminates the process before Function Compute can capture error details

ScenarioerrorMessageerrorTypestackTraceX-Fc-Error-Type header
Unhandled exceptionException messageFully qualified type (e.g., System.Exception)Full stack traceUnhandledInvocationError
Active exitGeneric process exit messageNot includedNot includedNot included

For a full list of error types that Function Compute can return, see Error types.

Handle exceptions

When a function throws an unhandled exception, Function Compute captures it and returns a structured JSON error response. The HTTP response includes the X-Fc-Error-Type: UnhandledInvocationError header.

The following example throws an exception from a StreamHandler function:

using System;
using System.IO;
using System.Threading.Tasks;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;

namespace Example
{
    public class Hello
    {
        public async Task<Stream> StreamHandler(Stream input, IFcContext context)
        {
            throw new Exception("oops");
        }

        static void Main(string[] args){}
    }
}

When the function is invoked, Function Compute returns:

{
    "errorMessage": "oops",
    "errorType": "System.Exception",
    "stackTrace": [...]
}
FieldDescription
errorMessageThe exception message
errorTypeThe fully qualified exception type
stackTraceThe stack trace at the point of failure

Avoid active exit

Calling System.Environment.Exit() in a handler causes the process to terminate before Function Compute can capture error details. The platform returns only a generic message with no stack trace:

{
    "errorMessage": "Process exited unexpectedly before completing request (duration: 45ms, maxMemoryUsage: 49MB)"
}
Warning

Do not call System.Environment.Exit() in function handlers. Active exit prevents Function Compute from capturing error information and stack traces, making errors difficult to diagnose.

Throw exceptions instead to get full error details in the response.

What's next