在Go语言中处理执行的函数切片的错误。

huangapple go评论82阅读模式
英文:

Error handling of executed slice of functions in Go

问题

我必须在一个for循环中运行未知数量的函数,并且当出现错误时(当其中一个函数返回错误时),我希望创建有意义的错误。

以下是一些代码:

package storage

import (
	"github.com/attilasatan/ankara/engine/indexer"
)

type NewHandler func(*indexer.Document) error

var NewHandlers []NewHandler


func AppendNewHandler(handler NewHandler) {
	NewHandlers = append(NewHandlers, handler)
}


func New(document *indexer.Document) (err error) {
	for i, handler := range NewHandlers {
		err = handler(document)
		if err != nil {
			err = errors.New(`New Handler error at index ` + string(i) + `
			original: 
			` + err.Error())
			return
		}
	}
	return
}

这是我处理错误的解决方案,但我对它不太满意,因为我只返回执行的函数的索引。

我的问题是,我能否收集有关返回非nil错误的函数的更多信息。

同时,任何建议都将不胜感激。

英文:

I must run an unknown number of functions in a for cycle and I want to create meaningful errors when something goes wrong (when error returns from one of them)

Here some code:

package storage

import (
	"github.com/attilasatan/ankara/engine/indexer"
)

type NewHandler func(*indexer.Document) error

var NewHandlers []NewHandler


func AppendNewHandler(handler NewHandler) {
	NewHandlers = append(NewHandlers, handler)
}


func New(document *indexer.Document) (err error) {
	for i, handler := range NewHandlers {
		err = handler(document)
		if err != nil {
			err = errors.New(`New Handler error at index ` + string(i) + `
			original: 
			` + err.Error())
			return
		}
	}
	return
}

This is my solution for error handling but i don't feel comfortable with it because I only return the index of the function that I executed.

My question is. Can I collect more information about the function that returned not nil error.

Also any kind of advises would be appreciated.

答案1

得分: 0

使用一个包含函数和任何元数据的结构体,而不仅仅是一个函数。类似这样:

type NewHandler struct {
    Handler func(*indexer.Document) error
    Data    string // 或者其他数据类型
}

同时确保你的切片保存的是指针,因为Go是按值传递的。

var NewHandlers []*NewHandler

然后,在循环中,可以这样使用:

for i, handler := range NewHandlers {
    err := handler.Handler(document)
    // ...
}

你可以将Data包含在错误信息中。

英文:

Use a struct that contains the func and any metadata instead of just a func. Something like this.

type NewHandler struct {
    Handler func(*indexer.Document) error
    Data string // or whatever data
}

Also make sure your slice holds pointers because go is pass-by-value.

var NewHandlers []*NewHandler

Then when you for loop, it goes like this.

for i, handler := range NewHandlers {
        err = handler.Handler(document)
        ....

And you can include your Data in the error.

huangapple
  • 本文由 发表于 2017年8月3日 00:37:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/45466440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定