February 15, 2021

Golang Error Handling:- Right ways of handling error

Golang is an open-source programming language the language is used for building efficient, reliable software. Moreover, it is more for solving error developers are finding go error handling to improve the performance of the application. Go is famous for not using the try/catch method while other languages are using it. Go treats error as the normal return value. 

Go Error Handling

So, are you seeking to learn more about Golang error handling? But I want to advise you to understand Error and error handling before going to learn about Golang error handling. And you just need to understand the error type. 

There are mainly 4 types of error:

  • Generated errors
  • Compile-time errors
  • logical errors
  • Run time errors

Defer, Panic, and Recover

Defer:

Defer is a language mechanism that puts functions into a stack. The defer function helps to execute reverse order. Defer mechanism clean up resources. you can see one of the examples below

resp, _ := http.Get("http://golang.org")

defer func () {

  if resp != nil {

     resp.Body.Close()

 }

}()

body, _ := ioutil.ReadAll(resp.Body)

Panic:

Panic is the function that will stop the normal execution flow that deferred function which runs as usual.

 func panic(v interface{}) 

Recover :

 Recover is an inbuilt function return value passing through a panic call this is a part of deferred below you can see the example coded. 

package main

import (  "fmt"  "github.com/pkg/errors")func A() {  defer fmt.Println("A")  defer func() {     if r := recover(); r != nil {        fmt.Printf("Panic: %+v\n", r)     }  }()  B()}func B() {  defer fmt.Println("B")  C()}func C() {  defer fmt.Println("C")  Break()}func Break() {  defer fmt.Println("D")  panic(errors.New("the show must go on"))}func main() {  A()}

Furthermore, Go error handling have a various method to deal with the run time error which makes it more demanding in the dev community because it also has rich snippet code solving the issue if you want to know more about Go error handling methods. I will suggest to you the best informative article just click on Read more