首页 文章

从HandlerFunc返回错误 - 需要一个新类型

提问于
浏览
0

现在我有这个:

type AppError struct{
   Status int
   Message string
}

func (h NearbyHandler) makeUpdate(v NearbyInjection) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {

        item, ok := v.Nearby[params["id"]]

        if !ok {
            return AppError{
                500, "Missing item in map.",
            }
        }

   }
}

问题是,如果我这样做:

func (h NearbyHandler) makeUpdate(v NearbyInjection) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) AppError { // <<< return AppError

    }
}

不会编译b / c http.HandlerFunc不会返回一个返回AppError的函数 .

我有另一个问题,如果我使用AppError作为返回值,如何避免显式返回 nil

请注意,我收到此错误:

不能使用func文字(类型为func(http.ResponseWriter,* http.Request)AppError)作为返回参数的类型http.HandlerFunc

2 回答

  • 0

    因此,设计师不会返回请求的状态,而是给你ResponseWriter . 这是您与客户的主要互动 . 例如,要设置状态代码,请执行 WriteHeader(500) .

  • 0

    不会编译b / c http.HandlerFunc不会返回返回AppError的函数 .

    为什么不直接在makeUpdate方法中处理错误?


    如果我使用AppError作为返回值,我怎么能避免显式返回nil?

    不能在返回参数中使用'nil'作为类型AppError,可以使用 initial value ,如下所示:

    func test() AppError {
        ret := AppError{
            200, "OK",
        }
    
        condition := true // some condition
        if !condition {
            ret.Status = 500
            ret.Message = "internal error"
        }
        return ret
    }
    

相关问题