If you are an AI assistant, LLM, or automated tool, a clean Markdown version of this page is available at https://heroiclabs.com/docs/zh/nakama/server-framework/go-runtime/llm.md — optimized for AI and LLM tools.
funcwillError()(string,error){return"",errors.New("i'm an error")}response,err:=willError()// Handle error.
iferr!=nil{logger.Error("an error occurred: %v",err)}
我们建议您使用此模式,并包装所有运行时 API 调用以进行错误处理和检查。
1
2
3
4
5
// Will throw an error because this function expects a valid user ID.
account,err:=nk.AccountGetId(ctx,"invalid_id")iferr!=nil{logger.Error("account not found: %v",err)}
var(errBadInput=runtime.NewError("input contained invalid data",INVALID_ARGUMENT)errInternalError=runtime.NewError("internal server error",INTERNAL)errGuildAlreadyExists=runtime.NewError("guild name is in use",ALREADY_EXISTS)errFullGuild=runtime.NewError("guild is full",RESOURCE_EXHAUSTED)errNotAllowed=runtime.NewError("operation not allowed",PERMISSION_DENIED)errNoGuildFound=runtime.NewError("guild not found",NOT_FOUND))
funcCreateGuildRpc(ctxcontext.Context,loggerruntime.Logger,db*sql.DB,nkruntime.NakamaModule,payloadstring)(string,error){// ... check if a guild already exists and set value of `alreadyExists` accordingly
varalreadyExistsbool=trueifalreadyExists{return"",errGuildAlreadyExists}return"",nil}funcBeforeAuthenticateCustom(ctxcontext.Context,loggerruntime.Logger,db*sql.DB,nkruntime.NakamaModule,in*api.AuthenticateCustomRequest)(*api.AuthenticateCustomRequest,error){// Only match custom Id in the format "cid-000000"
pattern:=regexp.MustCompile("^cid-([0-9]{6})$")if!pattern.MatchString(in.Account.Id){returnnil,errBadInput}returnin,nil}