普通网友 2017-08-02 16:37
浏览 73
已采纳

Go中执行的函数切片的错误处理

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条回答 默认 最新

  • dqu3974 2017-08-02 16:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题