golang统一错误处理

Posted 峰啊疯了

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang统一错误处理相关的知识,希望对你有一定的参考价值。

1.为什么要统一错误处理

统一错误处理的目的是为了前端开发接收到后端的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.共用错误处理golang统一错误处理_json

func HandleAllStatus(statusCode int, response *restful.Response, value interface) 
if value == 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 == nil
return statusCode


obj := make(map[string]interface)
switch tValue := value.(type)
case error:
json.Unmarshal([]byte(tValue.Error()), &obj)
default:
b, ok :Golang✔️走进 Go 语言✔️ 第十九课 错误处理 & 时间处理

Golang✔️走进 Go 语言✔️ 第十九课 错误处理 & 时间处理

golang 错误处理channel+error真的香

golang 错误处理channel+error真的香

golang 错误处理channel+error真的香

golang-错误处理