When processing errors in the code, the same code template is often repeated.

result, error := execute() if error != nil { return nil, error } 

How to avoid such repetitions?

3 answers 3

Read Rob Pike’s article “Errors as Values” :

"Programs are written on the basis of values, and knowing that errors are also values, they can be used in your code to implement some logic.

Of course, the general principle for handling any error value is to check for nil, but there are many other options for working with error values. And the use of these options will help make your program better, relieve it of the duplicate pattern code that appears when using standard checks.

Use language to simplify error handling.

But remember: whatever you do, you need to check the mistakes! "

That is, such checks cannot be avoided - you can only hide them inside wrapper functions or, alternatively, reduce their number by changing the application logic.

  • The link is good, but it is worth adding a couple of paragraphs in response to make it clear how this relates to the question "How to avoid such repetitions?" - jfs

More compact entry

 if result, error := execute(); error != nil { // Обработать ошибку } 

You can add deferred call defer

 defer hadleError() if result, error := execute(); error != nil { return nil, error } 

    Such checks can not be avoided. Go programmers must suffer for the lack of exceptions.

    Go authors write similar checks. So this can be considered a common way to handle errors.