Ral*_*veo 12 error-handling go
给出以下代码:
package main
import (
    "encoding/json"
    "fmt"
    "log"
)
type Employee struct {
    Id int "json:id"
}
func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee")
    }
    fmt.Println(string(b))
}
Run Code Online (Sandbox Code Playgroud)
_由于Employee结构定义良好,因此可以使用占位符可靠地忽略检查错误.理论上它应该永远不会失败,所以问题是忽略这种类型的错误并在这种类型的样板错误检查上节省一点是一个好习惯吗?
忽略看起来像这样:
package main
import (
    "encoding/json"
    "fmt"
)
type Employee struct {
    Id int "json:id"
}
func main() {
    b, _ := json.Marshal(&Employee{Id: 2})
    fmt.Println(string(b))
}
Run Code Online (Sandbox Code Playgroud)
    小智 7
正确的错误处理是良好软件的基本要求.
通常,您的代码不会失败.但是如果用户将此MarshalJSON方法reciver 添加到您的类型,它将失败:
func (t *Employee) MarshalJSON() ([]byte, error) {
    if t.Id == 2 {
        return nil, fmt.Errorf("Forbiden Id = %d", t.Id)
    }
    data := []byte(fmt.Sprintf(`{"Id":%d}`, t.Id))
    return data, nil
}
Run Code Online (Sandbox Code Playgroud)
此代码编译,但仅为Id == 2(The Go Playground)故意失败:  
package main
import (
    "encoding/json"
    "fmt"
    "log"
)
type Employee struct {
    Id int "json:id"
}
func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee", err)
    }
    fmt.Println(string(b))
}
func (t *Employee) MarshalJSON() ([]byte, error) {
    if t.Id == 2 {
        return nil, fmt.Errorf("Forbiden Id = %d", t.Id)
    }
    data := []byte(fmt.Sprintf(`{"Id":%d}`, t.Id))
    return data, nil
}
Run Code Online (Sandbox Code Playgroud)
此代码也编译,但失败(The Go Playground):
package main
import (
    "encoding/json"
    "fmt"
    "log"
)
type Employee struct {
    Id int "json:id"
}
func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee")
    }
    fmt.Println(string(b))
}
func (t Employee) MarshalJSON() ([]byte, error) {
    data := []byte(fmt.Sprint(t))
    return data, nil
}
Run Code Online (Sandbox Code Playgroud)