Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Error Handling

Go Error Handling

Go provides a very simple error-handling mechanism through its built-in error interface.

Go's error handling uses explicit error returns rather than traditional exception handling. This design makes the code logic clearer and allows developers to handle errors explicitly at compile time or runtime.

**Go's error handling mainly revolves around the following mechanisms: **

  1. error an interface: the standard representation of an error.
  2. Explicit return values: return errors through function return values.
  3. Custom errors: errors can be created via the standard library or custom methods.
  4. panic and recover: handle unrecoverable serious errors.

The error interface

The Go standard library defines an error interface, representing an abstraction of an error.

The error type is an interface type; here is its definition:



type error interface {

    Error() string

}

Creating errors with the errors package

We can generate error messages in code by implementing the error interface type.

Create a simple error:

Example

package

main

import

(

   

"errors"

   

"fmt"

)

func

main

()

{

    err

:=

errors

.

New

(

"this is an error"

)

    fmt

.

Println

(

err

)

// Output: this is an error

}

Functions usually return error information in the last return value; using errors.New can return an error message:



func Sqrt(f float64) (float64, error) {

    if f < 0 {

        return 0, errors.New("math: square root of negative number")

    }

    // 实现

}

In the following example, we pass a negative number when calling Sqrt, and then get a non-nil error object. Comparing this object with nil yields true, so fmt.Println (the fmt package calls the Error method when handling an error) is called to output the error. See the sample code below:



result, err:= Sqrt(-1)



if err != nil {

   fmt.Println(err)

}


Explicitly returning errors

In Go, errors are usually returned as function return values, and developers need to check and handle them explicitly.

Explicitly return the error:

Example

package

main

import

(

       

"errors"

       

"fmt"

)

func

divide

(

a

,

b

int

)

(

int

,

error

)

{

       

if

b

==

0

{

               

return

0

,

errors

.

New

(

"division by zero"

)

       

}

       

return

a

/

b

,

nil

}

func

main

()

{

        result

,

err

:=

divide

(

10

,

0

)

       

if

err

!=

nil

{

                fmt

.

Println

(

"Error:"

,

err

)

       

}

else

{

                fmt

.

Println

(

"Result:"

,

result

)

       

}

}

Output:



Error: division by zero


Custom errors

By defining custom types, you can extend the error interface.

Custom error type:

Example

package

main

import

(

       

"fmt"

)

type

DivideError

struct

{

        Dividend

int

        Divisor  

int

}

func

(

e

DivideError

)

Error

()

string

{

       

return

fmt

.

Sprintf

(

"cannot divide %d by %d"

,

e

.

Dividend

,

e

.

Divisor

)

}

func

divide

(

a

,

b

int

)

(

int

,

error

)

{

       

if

b

==

0

{

               

return

0

,

&DivideError

{

Dividend

:

a

,

Divisor

:

b

}

       

}

       

return

a

/

b

,

nil

}

func

main

()

{

        _

,

err

:=

divide

(

10

,

0

)

       

if

err

!=

nil

{

                fmt

.

Println

(

err

)

// Output: cannot divide 10 by 0

       

}

}


The fmt package and error formatting

fmt The package provides support for formatting error output:

Example

package

main

import

(

   

"fmt"

)

// Define a DivideError struct

type

DivideError

struct

{

    dividee

int

    divider

int

}

// Implementation error an interface

func

(

de

DivideError

)

Error

()

string

{

    strFormat

:=

    Cannot proceed, the divider is zero.     dividee: %d     divider: 0

   

return

fmt

.

Sprintf

(

strFormat

,

de

.

dividee

)

}

// Define a int function for division operations of the type

func

Divide

(

varDividee

int

,

varDivider

int

)

(

result

int

,

errorMsg

string

)

{

   

if

varDivider

==

0

{

            dData

:=

DivideError

{

                    dividee

:

varDividee

,

                    divider

:

varDivider

,

           

}

            errorMsg

=

dData

.

Error

()

           

return

   

}

else

{

           

return

varDividee

/

varDivider

,

""

   

}

}

func

main

()

{

   

// Normal case

   

if

result

,

errorMsg

:=

Divide

(

100

,

10

);

errorMsg

==

""

{

            fmt

.

Println

(

"100/10 = "

,

result

)

   

}

   

// Returns an error message when the divisor is zero

   

if

_

,

errorMsg

:=

Divide

(

100

,

0

);

errorMsg

!=

""

{

            fmt

.

Println

(

"errorMsg is: "

,

errorMsg

)

   

}

}

Running the above program, the output is:



100/10 =  10

errorMsg is:  

    Cannot proceed, the divider is zero.

    dividee: 100

    divider: 0




Using errors.Is and errors.As

Starting from Go 1.13, theerrors package introduced errors.Is and errors.As for handling error chains:

errors.Is

Check whether an error is a specific error or is wrapped from that error.

Example

package

main

import

(

       

"errors"

       

"fmt"

)

var

ErrNotFound

=

errors

.

New

(

"not found"

)

func

findItem

(

id

int

)

error

{

       

return

fmt

.

Errorf

(

"database error: %w"

,

ErrNotFound

)

}

func

main

()

{

        err

:=

findItem

(

1

)

       

if

errors

.

Is

(

err

,

ErrNotFound

)

{

                fmt

.

Println

(

"Item not found"

)

       

}

else

{

                fmt

.

Println

(

"Other error:"

,

err

)

       

}

}

errors.As

Convert an error to a specific type for further handling.

Example

package

main

import

(

       

"errors"

       

"fmt"

)

type

MyError

struct

{

        Code

int

        Msg  

string

}

func

(

e

MyError

)

Error

()

string

{

       

return

fmt

.

Sprintf

(

"Code: %d, Msg: %s"

,

e

.

Code

,

e

.

Msg

)

}

func

getError

()

error

{

       

return

&MyError

{

Code

:

404

,

Msg

:

"Not Found"

}

}

func

main

()

{

        err

:=

getError

()

       

var

myErr

MyError

       

if

errors

.

As

(

err

,

&myErr

)

{

                fmt

.

Printf

(

"Custom error - Code: %d, Msg: %s\n"

,

myErr

.

Code

,

myErr

.

Msg

)

       

}

}


panic and recover

Go's panic is used to handle unrecoverable errors, and recover is used to recover from a panic.

panic:

recover:

Example

package

main

import

"fmt"

func

safeFunction

()

{

       

defer

func

()

{

               

if

r

:=

recover

();

r

!=

nil

{

                        fmt

.

Println

(

"Recovered from panic:"

,

r

)

               

}

       

}()

       

panic

(

"something went wrong"

)

}

func

main

()

{

        fmt

.

Println

(

"Starting program..."

)

        safeFunction

()

        fmt

.

Println

(

"Program continued after panic"

)

}

The output of the code above is:

Starting program...

Recovered from panic: something went wrong

Program continued after panic