ZhangZhihui's Blog  

Problem: You want to create custom errors to communicate more information about the error encountered.


Solution: Create a new string - based error or implement the error interface by creating a struct with an Error method that returns a string.

 

There are different ways of creating errors (in a good way).
Using a string - based error

    err := errors.New("Syntax error in the code")

    err := fmt.Errorf("Syntax error in the code at line %d", line)

Implementing the error interface

type error interface {
    Error() string
}

As you can see, any struct with a method named Error that returns a string is an error. So if you want to define a custom error to return a custom error message, implement a struct and add an Error method. For example, let’s say you are writing a program used for communications and want to create a custom error to represent an error during communications:

type CommsError struct{}

func (m CommsError) Error() string {
    return "An  error  happened  during  data  transfer."
}

You want to provide information about where the error came from. To do this, you can create a custom error to provide the information. Of course, you usually wouldn’t override Error ; you can add fields and other methods to your custom error to carry more information:

type SyntaxError struct {
    Line int
    Col  int
}

func (err *SyntaxError) Error() string {
    return fmt.Sprintf("Error  at  line  %d,  column  %d", err.Line, err.Col)
}

When you get such an error, you can typecast it using the “comma, ok” idiom (because if you typecast it and it’s not that type, it will panic), and extract the additional data for your processing:

    if err != nil {
        err, ok := err.(*SyntaxError)
        if ok {
            //  do  something  with  the  error
        } else {
            //  do  something  else
        }
    }

 

复制代码
package main

import "fmt"

type CommsError struct{}

func (m CommsError) Error() string {
    return "An  error  happened  during  data  transfer."
}

type SyntaxError struct {
    Line int
    Col  int
}

func (err *SyntaxError) Error() string {
    return fmt.Sprintf("Error  at  line  %d,  column  %d", err.Line, err.Col)
}

func main() {
    var err1 CommsError
    fmt.Println(err1)

    err2 := SyntaxError{Line: 6, Col: 12}
    fmt.Println(err2)

    err3 := SyntaxError{Line: 6, Col: 12}
    fmt.Println(&err3)
}
复制代码

 

zzh@ZZHPC:/zdata/MyPrograms/Go/study$ go run main.go
An  error  happened  during  data  transfer.
{6 12}
Error  at  line  6,  column  12

 

posted on   ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示