Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic rules of Go error handling

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the basic rules of Go error handling". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the basic rules of Go error handling.

Rule 1-do not ignore errors

Sooner or later your function will return a failure, and you will spend a lot of time determining the cause and restoring the program.

Deal with these errors. If you are in a hurry or too tired-then take a break.

Package main

Import (

"fmt"

"time"

)

Func main () {

/ / Don't ignore the mistakes here

Lucky, _: = ifItCanFailItWill ()

}

Func ifItCanFailItWill () (string, error) {

NowNs: = time.Now () .Nanosecond ()

If nowNs% 2 = = 0 {

Return "shinny desired value", nil

}

Return "", fmt.Errorf ("I will fail one day, handle me")

}

Rule 2

Return an error as soon as possible

It may be natural to focus on the "happy path" of code execution first, but I prefer to start with validation and return the value at the end when everything is 100% complete.

Poor scalability:

Func nah () (string, error) {

NowNs: = time.Now () .Nanosecond ()

If nowNs% 2 = = 0 & & isValid () {

Return "shinny desired value", nil

}

Return "", fmt.Errorf ("I will fail one day, handle me")

}

More professional:

Func earlyReturnRocks () (string, error) {

NowNs: = time.Now () .Nanosecond ()

If nowNs 2 > 0 {

Return "", fmt.Errorf ("time dividability must be OCD compliant")

}

If! isValid () {

Return ", fmt.Errorf (" a different custom, specific, helpful error message ")

}

Return "shinny desired value", nil

}

Advantages?

Easier to read

Easily add more validation

Less nested code (especially in loops)

Clear focus on security and error handling

Each if condition may have a specific error message

Rule 3

Return value or error (but not both)

I see developers using both return values and errors. This is a bad habit. Avoid doing this.

Confusing:

Func validateToken () (desiredValue string, expiredAt int, err error) {

NowNs: = time.Now () .Nanosecond ()

If nowNs 2 > 0 {

/ / THE expiredAt (nowNs) SHOULD NOT BE RETURNED TOGETHER WITH THE ERR

Return "", nowNs, fmt.Errorf ("token expired")

}

Return "shinny desired value", 0, nil

}

Insufficient?

The method signature is not clear

The method must be reverse-engineered to understand the value returned and when to return

Yes, sometimes you need to return additional information about the error, in which case, create a new dedicated Error object.

More professional:

Package main

Import (

"fmt"

"github.com/davecgh/go-spew/spew"

"time"

)

Func main () {

Value, err: = validateToken ()

If err! = nil {

Spew.Dump (err.Error ())

}

Spew.Dump (value)

}

/ / Compatible with error built-in interface.

/ /

/ / type error interface {

/ / Error () string

/ /}

Type TokenExpiredErr struct {

ExpiredAt int

}

Func (e TokenExpiredErr) Error () string {

Return fmt.Sprintf ("token expired at block d", e.expiredAt)

}

Func validateToken () (desiredValue string, err error) {

NowNs: = time.Now () .Nanosecond ()

If nowNs 2 > 0 {

Return "", TokenExpiredErr {expiredAt: nowNs}

}

Return "shinny desired value", nil

}

Rule 4

Log or return (but not at the same time)

When you write an error to log, you are dealing with it. Don't return the error to the caller and force him to handle it!

Why? Because you do not want to log the same message two or more times:

Package main

Import (

"fmt"

"os"

"time"

)

Func main () {

/ / validateToken () is already doing the logging

/ / but I didn't reverse engineer the method so I don't know about that

/ / and now I will unfortunately end up with the same message being logged twice

_, err: = validateToken ()

If err! = nil {

/ / I have nowhere to return it, SO I RIGHTFULLY LOG IT

/ / And I will not ignore a possible error writing err

_, err = fmt.Fprint (os.Stderr, fmt.Errorf ("validating token failed.% s", err.Error ()

If err! = nil {

/ / Extremely rare, no other choice

Panic (err)

}

Os.Exit (1)

}

}

Type TokenExpiredErr struct {

ExpiredAt int

}

Func (e TokenExpiredErr) Error () string {

Return fmt.Sprintf ("token expired at block d", e.expiredAt)

}

Func validateToken () (desiredValue string, err error) {

NowNs: = time.Now () .Nanosecond ()

If nowNs 2 > 0 {

/ / DO NOT LOG AND RETURN

/ / DO NOT LOG AND RETURN

/ / DO NOT LOG AND RETURN

Fmt.Printf ("token validation failed. Token expired at d", nowNs)

Return "", TokenExpiredErr {expiredAt: nowNs}

}

Return "shinny desired value", nil

}

Logging and returning errors can lead to confusing output:

Token validation failed. Token expired at 115431493validating token failed. Token expired at block 115431493

More professional: log or return an error, choose one:

Validating token failed. Token expired at block 599480733

Rule 5

Configure if err! = nil as a macro in IDE

Thank you for your reading, these are the contents of "what are the basic rules of Go error handling". After the study of this article, I believe you have a deeper understanding of what the basic rules of Go error handling are, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report