前言
本文介绍go-kit自定义error处理,本文地址: github地址,这样做的目的是返回自定义的文本错误,将http状态码直接写进http status code里面,这有利于日志错误分类的收集和统计
1.自定义一个解码函数MyErrorEncoder
在util/myerror.go里面实现官方的error接口,便于实现我们自己定义的error方法,并且自定义一个解码函数MyErrorEncoder
func MyErrorEncoder(_ context.Context, err error, w http.ResponseWriter) {
contentType, body := "application/json,charset=utf-8", []byte(err.Error())
w.Header().Set("content-type", contentType)
if err, ok := err.(*MyError); ok {
w.WriteHeader(err.Code)
} else {
w.WriteHeader(500)
}
w.Write(body)
}
2.在options里面包装
在transport.go的MakeHttpHandler函数里面将MyErrorEncoder在[]kithttp.ServerOption{}里面包裹进去
3.在service自定义一个错误
在userservice/service.go自定义一个错误ErrorUserNotFound = util.NewMyError(406, “用户不存在”),返回一个业务错误“用户不存在”,MyErrorEncoder函数将状态码直接写进http status code里面,这有利于日志错误分类的收集和统计
4.调试
访问localhost:8000/user/2 打开浏览器的调试工具会发现status code是406,返回错误为用户不存在