我们经常用的panic是会让程序挂掉,生产环境显然不合适,但是错误怎么避免,Go不像Java有try catch,在简洁的同时也有如何处理异常错误的问题。
我们可以用闭包,闭包的思路就是不会改变外部的东西,也就是说我们处理了错误其实错误还是存在,只是使用了错误。
举例
func viewHandler(w http.ResponseWriter, r *http.Request) { imageId := r.FormValue("id") imagePath := UPLOAD_DIR + "/" + imageId if exists := isExists(imagePath); !exists { http.NotFound(w, r) return } w.Header().Set("Content-type", "iamge") http.ServeFile(w, r, imagePath) }
这是一个handlefunc
func safeHandler(fn http.HandlerFunc) http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { defer func() { if e, ok := recover().(error); ok { http.Error(writer, e.Error(), http.StatusInternalServerError) } }() fn(writer, request) } }
这是一个接受handlefunc的函数,把func传进去,处理err再返回一个func。这里闭包中调用了fn,同时加了一个defer专门处理err,是一个很不错的方式。
http.HandleFunc("/view", safeHandler(viewHandler))
这是如何使用。
扫描二维码关注公众号,回复:
9426518 查看本文章