普通网友 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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号