golang统一错误处理

人生必须的知识就是引人向光明方面的明灯。这篇文章主要讲述golang统一错误处理相关的知识,希望能为你提供帮助。
1.为什么要统一错误处理
【golang统一错误处理】统一错误处理的目的是为了前端开发接收到后端的statuscode,之后便于前端逻辑上开发,以及开发。200代表成功,500失败,400代表找不到、禁止等异常
2.后端封装统一接口

/**
* 统一处理
* 错误码,response,返回内容,error
*/
func HandleResult(statusCode int, response *restful.Response, value interface, err error)
if err != nil
HandleAllStatus(parseValue(err, statusCode), response, err)
return


if statusCode == http.StatusOK
HandleSuccess(response, value)
return

// 解析其他错误
HandleAllStatus(parseValue(value, statusCode), response, value)

3.核心函数
func handle(statusCode int, response *restful.Response, req *restful.Request, err error)
_, fn, line, _ := runtime.Caller(2)
klog.Errorf("%s:%d %v", fn, line, err)
http.Error(response, sanitizer.Replace(err.Error()), statusCode)

打印错误日志,哪个文件函数多少行,以及错误原因
4.常见错误处理
func HandleInternalError(response *restful.Response, req *restful.Request, err error)
handle(http.StatusInternalServerError, response, req, err)


// HandleBadRequest writes http.StatusBadRequest and log error
func HandleBadRequest(response *restful.Response, req *restful.Request, err error)
handle(http.StatusBadRequest, response, req, err)


func HandleNotFound(response *restful.Response, req *restful.Request, err error)
handle(http.StatusNotFound, response, req, err)


func HandleForbidden(response *restful.Response, req *restful.Request, err error)
handle(http.StatusForbidden, response, req, err)


func HandleUnauthorized(response *restful.Response, req *restful.Request, err error)
handle(http.StatusUnauthorized, response, req, err)


func HandleTooManyRequests(response *restful.Response, req *restful.Request, err error)
handle(http.StatusTooManyRequests, response, req, err)


func HandleConflict(response *restful.Response, req *restful.Request, err error)
handle(http.StatusConflict, response, req, err)

5.共用错误处理
func HandleAllStatus(statusCode int, response *restful.Response, value interface)
if value =https://www.songbingjia.com/android/= nil
response.WriteHeader(statusCode)
return


switch ee := value.(type)
case error:
handle(statusCode, response, nil, ee)
case string:
response.WriteHeader(statusCode)
response.WriteAsJson(value)
return
default:
response.WriteHeader(statusCode)
//处理是否为byte数组
b, ok := value.([]byte)
if ok
response.Write(b)
else
response.WriteEntity(value)



6.解析错误原因
func parseValue(value interface, statusCode int) int
if value =https://www.songbingjia.com/android/= nil
return statusCode


obj := make(map[string]interface)
switch tValue := value.(type)
case error:
json.Unmarshal([]byte(tValue.Error()), & obj)
default:
b, ok :

    推荐阅读