Go - Creating Customized Errors

发布时间 2023-09-29 10:20:34作者: ZhangZhihuiAAA

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 
      } 
}