wa-lang.org/wazero@v1.0.2/sys/error.go (about)

     1  // Package sys includes constants and types used by both public and internal APIs.
     2  package sys
     3  
     4  import (
     5  	"fmt"
     6  )
     7  
     8  // ExitError is returned to a caller of api.Function still running when
     9  // api.Module CloseWithExitCode was invoked. ExitCode zero value means success,
    10  // while any other value is an error.
    11  //
    12  // Here's an example of how to get the exit code:
    13  //
    14  //	main := module.ExportedFunction("main")
    15  //	if err := main(ctx); err != nil {
    16  //		if exitErr, ok := err.(*sys.ExitError); ok {
    17  //			// If your main function expects to exit, this could be ok if Code == 0
    18  //		}
    19  //	--snip--
    20  //
    21  // Note: While possible the reason of this was "proc_exit" from "wasi_snapshot_preview1", it could be from other host
    22  // functions, for example an AssemblyScript's abort handler, or any arbitrary caller of CloseWithExitCode.
    23  //
    24  // See https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#proc_exit and
    25  // https://www.assemblyscript.org/concepts.html#special-imports
    26  type ExitError struct {
    27  	moduleName string
    28  	exitCode   uint32
    29  }
    30  
    31  func NewExitError(moduleName string, exitCode uint32) *ExitError {
    32  	return &ExitError{moduleName: moduleName, exitCode: exitCode}
    33  }
    34  
    35  // ModuleName is the api.Module that was closed.
    36  func (e *ExitError) ModuleName() string {
    37  	return e.moduleName
    38  }
    39  
    40  // ExitCode returns zero on success, and an arbitrary value otherwise.
    41  func (e *ExitError) ExitCode() uint32 {
    42  	return e.exitCode
    43  }
    44  
    45  // Error implements the error interface.
    46  func (e *ExitError) Error() string {
    47  	return fmt.Sprintf("module %q closed with exit_code(%d)", e.moduleName, e.exitCode)
    48  }
    49  
    50  // Is allows use via errors.Is
    51  func (e *ExitError) Is(err error) bool {
    52  	if target, ok := err.(*ExitError); ok {
    53  		return e.moduleName == target.moduleName && e.exitCode == target.exitCode
    54  	}
    55  	return false
    56  }