This topic describes how to handle errors in the Go runtime environment.

If an error occurs, the HTTP response header contains X-Fc-Error-Type such as X-Fc-Error-Type: UnhandledInvocationError. For more information about error types of Function Compute, see Error handling.

Function Compute can return errors in the following ways:

  • Specify the error message to return in the handler function. Sample code:
    package main
    
    import (
        "errors"
        "fmt"
    
        "github.com/aliyun/fc-runtime-go-sdk/fc"
    )
    
    func HandleRequest() error {
        fmt.Println("hello world")
        return errors.New("something is wrong")
    }
    
    func main() {
        fc.Start(HandleRequest)
    }

    After the function is invoked, the following response is returned:

    {
      "errorMessage": "something is wrong!",
      "errorType": "errorString"
    }
  • Use panic to return an error message. Sample code:
    package main
    
    import (
        "fmt"
    
        "github.com/aliyun/fc-runtime-go-sdk/fc"
    )
    
    func HandleRequest() error {
        fmt.Println("hello world")
        panic("Error: something is wrong")
        return nil
    }
    
    func main() {
        fc.Start(HandleRequest)
    }

    After the function is invoked, the following response is returned. In this example, some stack information is omitted.

    {
      errorMessage: 'Error: something is wrong',
      errorType: 'string',
      stackTrace: [
        {
          path: 'github.com/aliyun/fc-runtime-go-sdk/fc/errors.go',
          line: 39,
          label: 'fcPanicResponse'
        },
        {
          path: 'github.com/aliyun/fc-runtime-go-sdk/fc/function.go',
          line: 84,
          label: '(*Function).Invoke.func1'
        },
        ...
        ...
        ...
        { path: 'code/main.go', line: 22, label: 'main' },
        { path: 'runtime/proc.go', line: 255, label: 'main' },
        null
      ]
    }
  • Use error handling code such as log.Fatal that contains os.Exit(1).
    Notice We recommend that you do not use this method. If you use this method, no error message or stack information is returned upon an exit.
    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/aliyun/fc-runtime-go-sdk/fc"
    )
    
    func HandleRequest() error {
        fmt.Println("hello world")
        log.Fatal("something is wrong")
        return nil
    }
    
    func main() {
        fc.Start(HandleRequest)
    }

    After the function is invoked, the following response is returned:

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