This topic describes how to handle errors in the Go runtime environment.
When an error occurs, the HTTP header of the response to the function invocation contains the X-Fc-Error-Type
field, which indicates the error type. Example: X-Fc-Error-Type: UnhandledInvocationError
. For information about the error types of Function Compute, see the "Error handling" section of the Basics topic.
The following items describe the methods that Function Compute uses to return error information:
Return error information 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) }
When the function is invoked, the following response is returned:
{ "errorMessage": "something is wrong!", "errorType": "errorString" }
Use panic to return error information. 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) }
When 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' }, { path: 'runtime/asm_amd64.s', line: 1581, label: 'goexit' } ] }
Use error code that contains
os.Exit(1)
, such aslog.Fatal
.ImportantWe 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) }
When the function is invoked, the following response is returned:
{ errorMessage: 'Process exited unexpectedly before completing request (duration: 0ms, maxMemoryUsage: 8MB)' }