现在我有这个:
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 回答
因此,设计师不会返回请求的状态,而是给你ResponseWriter . 这是您与客户的主要互动 . 例如,要设置状态代码,请执行
WriteHeader(500)
.为什么不直接在makeUpdate方法中处理错误?
不能在返回参数中使用'nil'作为类型AppError,可以使用 initial value ,如下所示: