惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
The Cloudflare Blog
博客园 - 聂微东
博客园 - 司徒正美
量子位
博客园 - 三生石上(FineUI控件)
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
G
Google Developers Blog
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
Y
Y Combinator Blog
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
有赞技术团队
有赞技术团队
A
About on SuperTechFans

博客园 - Mr__BRIGHT

Jupyter Notebook导入自定义模块时ImportError Pandas数据处理(2): 数据透视表,行转列、列转行、以及一行生成多行 Pandas数据处理(1): 基础方法整理 Win10-PowerShell使用conda activate激活环境无效问题及常用Conda操作 Spring AOP动态代理实现,解决Spring Boot中无法正常启用JDK动态代理的问题 CentOS常用的文件操作命令 win10周年更新后程序各种卡死,进程无法结束怎么破? GIT分支管理模型 - Mr__BRIGHT - 博客园 CentOS访问Windows共享文件夹的方法 GIT FLOW 时序图 - Mr__BRIGHT Hyper-v虚拟机文件VHDX与VHD的格式转换 CentOS详解top命令各个数据的含义 CentOS网络配置 git svn clone时间估算 使用git svn clone迁移svn仓库(保留提交记录) .NET 4.5+项目迁移.NET Core的问题记录 老毛桃u盘装系统制作工具 一位39岁程序员的困惑:知道得越多编程越慢怎么办? 程序员的回归式进化
Golang 如何统一处理HTTP请求中的异常捕获
Mr__BRIGHT · 2017-09-21 · via 博客园 - Mr__BRIGHT

最近写go,路由选择httprouter,现在希望在不修改httprouter源码的前提下,对所有注册的路由handle进行异常捕获。

golang使用panic()产生异常,然后可以recover()来捕获到异常,否则主程序直接宕掉,这是我们不希望看到的。
或者全程检查error,不主动抛出异常。即便这样,可能异常依然不能避免。

func RegRouters(r *httprouter.Router) {
	r.GET("/", Home)
	r.GET("/contact", Contact)
}

func Home(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
}

func Contact(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
}

正常的路由表长这样,在C#中相当于对每个请求加try...catch,将业务上代码包裹起来。
golang同理:

func RegRouters(r *httprouter.Router) {
	r.GET("/", WrapHandle(Home))
	r.GET("/contact", WrapHandle(Contact))
}

WrapHandle需要有一个handle类型的参数,同时返回值要能被httprouter接收

func WrapHandle(handle httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
		handle(w, r, p)
	}
}

加一个上下文,把handle简化一下

func WrapHandle(handle func(ctx *context.Context)) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		defer func() {
			if pr := recover(); pr != nil {
				fmt.Println("panic recover: %v", pr)
				debug.PrintStack()
			}
		}()
		ctx := context.NewContext(w, r, p)
		handle(ctx)
	}
}
func Home(ctx *context.Context) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
}

func Contact(ctx *context.Context) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
	id = ctx.FormInt64("id") //通过context从FORM取值,并转换为int64
}

这里加了一个context包,handle的参数也减少到一个,主要是context上可以做更多的事情。

一个简单的请求上下文的原型:

type Context struct {
	responseWriter http.ResponseWriter
	request        *http.Request
	params         httprouter.Params
	Data           map[string]interface{}
}

func NewContext(w http.ResponseWriter, r *http.Request, params httprouter.Params) *Context {
	ctx := new(Context)
	ctx.responseWriter = w
	ctx.request = r
	ctx.params = params
	ctx.Data = make(map[string]interface{})
	return ctx
}

func (ctx *Context) FormValue(name string) string {
	return ctx.request.FormValue(name)
}

func (ctx *Context) FormInt64(name string) int64 {
	value, _ := strconv.ParseInt(ctx.FormValue(name), 10, 64)
	return value
}

//更多扩展....

好了,先到这里,希望对你有帮助。