duanfan1965 2016-07-13 21:22
浏览 48
已采纳

如何在Golang中将面向用户的错误与内部错误完全区分开?

I am running into a common pattern where I have a function that takes user input, and either returns a successful output value or an error. But it can return different types of errors, some of which are the result of bad user input and others which are the result of internal errors (DB unavailable, for instance).

My functions have signatures that look like this:

// ProcessInput takes a user-input string and returns a processed value
func ProcessInput(input string) (ProcessedValue, error, error) {}

The first return value is meaningful (not nil) if no errors were encountered, the second return value is an error if the user input failed validation, and the third return value is an error if an unexpected internal error occurred.

This works fine but it does not feel very clean, and it's not obvious from looking at the signature what the different errors are. I considered naming the error returns but I don't like the side-effects of naming return parameters.

Are there any other patterns I could apply that are cleaner? Should I have a single error return and distinguish by type on the caller side?

  • 写回答

2条回答 默认 最新

  • duanjinchi1982 2016-07-13 21:30
    关注

    Returning multiple error does not seem very Go-like to me.

    Why not have an interface called UserError that defines a method that returns a message suitable to show the user. If the returned error does not implement UserError, show a standard "Internal Server Error" message. Example:

    type UserError interface {
        error
        UserError() string
    }
    
    type emptyInput struct {}
    
    func (e emptyInput) Error() string {
        return e.UserError()
    }    
    
    func (emptyInput) UserError() string {
        return "Empty input"
    }
    
    func ProcessInput(input string) (*ProcessedValue, error) {
        if input == "" {
            return nil, &emptyInput{}
        }
    }
    
    func httpHandler() {
        val, err := ProcessInput(input)
        if err != nil {
            if userErr := err.(UserError); userErr != nil {
                // show userError.UserError() to user
            } else {
                // Log error
                // show Internal server error message
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置