// 内部的错误map,用来对应 错误号和错误信息 var errCodeMap = map[MyErrorCode]string{ ErrorBookNotFoundCode: "Book was not found", ErrorBookHasBeenBorrowedCode: "Book has been borrowed", }
// Step2: 处理 // 特殊业务场景:如果发现书被借走了,下次再来就行了,不需要作为错误处理 if err != nil { // 提取error这个interface底层的错误码,一般在API的返回前才提取 // As - 获取错误的具体实现 var myError = new(MyError) if errors.As(err, &myError) { fmt.Printf("error code is %d, message is %s\n", myError.Code, myError.Message) }
// 特殊逻辑: 对应场景2,指定错误(ErrorBookHasBeenBorrowed)时,打印即可,不返回错误 // Is - 判断错误是否为指定类型 if errors.Is(err, ErrorBookHasBeenBorrowed) { fmt.Printf("book %s has been borrowed, I will come back later!\n", bookName) err = nil } }
Jane Eyre start === error code is 2, message is Book has been borrowed book Jane Eyre has been borrowed, I will come back later! === Jane Eyre end
打印被借走的提示,而错误被 err = nil 屏蔽。
3. 发现图书馆不存在这本书 - War and Peace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
War and Peace start === error code is 1, message is Book was not found Book was not found bookName is War and Peace main.searchBook /GoProject/godemo/main.go:98 main.borrowOne /GoProject/godemo/main.go:71 main.main /GoProject/godemo/main.go:60 runtime.main /usr/local/go1.13.5/src/runtime/proc.go:203 runtime.goexit /usr/local/go1.13.5/src/runtime/asm_amd64.s:1357 === War and Peace end