栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go-kit 自定义异常错误处理

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go-kit 自定义异常错误处理

前言

在go的默认错误实现中,任何异常错误都会返回500,实际项目中我们需要根据异常的不同去设置code的不同

一、自定义Error处理器
package ErrorHandler

import (
	"context"
	"net/http"
)

type MyError struct{
	Code    int
	Message string
}

func NewMyError(code int, msg string) error {
	return &MyError{Code: code, Message: msg}
}

func (this *MyError) Error() string {
	return this.Message
}
func MyErrorEncoder(ctx context.Context, err error, w http.ResponseWriter) {
	contentType, body := "text/plain; charset=utf-8", []byte(err.Error())
	//设置请求头
	w.Header().Set("Content-type", contentType)
	// 通过类型断言判断当前error的类型,走相应的处理
	if myerr, ok := err.(*MyError); ok {
		w.WriteHeader(myerr.Code)
		w.Write(body)
	} else {
		// 如果不是自定义错误处理
		w.WriteHeader(500)
		w.Write(body)
	}
}

整合Go-kit

基于go-kit的ServerOption传入

opts := []httpTransport.ServerOption{
		httpTransport.ServerErrorEncoder(ErrorHandler.MyErrorEncoder),
		httpTransport.ServerBefore(httpTransport.PopulateRequestContext),
	}
示例返回

如果出现异常,例如限流器出现的toot many request异常,想要返回自定义的429,就可以用自定义的异常错误处理。

return nil, utils.NewMyError(429, "toot many request") 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906877.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号