go中使用panic将异常转化为error

golang中提供panic和reover函数,用于将程序未可知的异常转化为错误,不得不说这点还是比c要多了些控制的权利,而又比c++的异常更为灵活。

[source lang=”c”]
package main

import (
"fmt"
"math"
)

func ConvertInt64To32(x int64) int{
if (math.MinInt32 <= x && x <= math.MaxInt32){
return int(x)
}

panic(fmt.Sprintf("%d is out of the int32 rang", x))
}

func IntFromInt64(x int64) (i int, err error){
defer func(){
if e:= recover(); e!= nil{
err = fmt.Errorf("%v", e)
}
}()

i = ConvertInt64To32(x)

return i,nil
}

func main(){
var x int64

x = 5
i, err := IntFromInt64(x)
fmt.Printf("%d %s\n", i, err)

x = math.MaxInt32 + 3
i, err = IntFromInt64(x)
fmt.Printf("%d %s\n", i,err)

}

[/source]

如果需要保证http服务器不因为panic而异常退出可以使用以下方式:

[source lang=”c”]
func homePage(writer http.ResponseWriter, request *http.Request) {
//…….
}

func logPanics(function func(http.ResponseWriter,*http.Request))
func(http.ResponseWriter, *http.Request) {
return func(writer http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
}
}()

function(writer, request)
}
}

http.HandleFunc("/", logPanics(homePage))

// 为每个路径处理都加上则可以避免服务器down机
http.HandleFunc("/", logPanics(homePage))
// http.HandleFunc("/foo", logPanics(fooFun))

[/source]

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注