SlideShare a Scribd company logo
Defer,
panic,
recover.
Joris Bonnefoy
DevOps @ OVH
@devatoria
Definitions
Defer
Defer
● A defer statement allows you to execute a function when the calling function returns
● When you call the defer statement, the given function is pushed into a list
● After the surrounding function returned, functions in the list are executed in LIFO order
● Defer is commonly used to improve readability
Without defer
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
dst, err := os.Create(dstName)
if err != nil {
src.Close()
return
}
written, err = io.Copy(dst, src)
dst.Close()
src.Close()
return
}
With defer
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
defer src.Close()
dst, err := os.Create(dstName)
if err != nil {
return
}
defer dst.Close()
return io.Copy(dst, src)
}
3 simple defer rules to know
1. A deferred function's arguments are evaluated when the defer
statement is evaluated.
func main() {
i := 0
defer fmt.Println(i)
i++
}
func main() {
i := 0
defer func() {
fmt.Println(i)
}()
i++
}
0 1
func main() {
for i := 0; i < 4; i++ {
defer fmt.Print(i)
}
}
2. Deferred function calls are executed in Last In First Out order
after the surrounding function returns.
3210
func f() (i int) {
defer func() { i++ }()
return 2
}
func main() {
fmt.Println(f())
}
3. Deferred functions may read and assign to the returning
function's named return values.
3
Panic
Panic
● A built-in function from the runtime
● When the function F calls the panic function
○ It stops the actual execution
○ Deferred functions in F are executed
○ F returns to its caller
○ For the caller, F acts like a call to panic
○ Once all the functions of the panicking goroutine have returned, the program crashes
package main
import "fmt"
func main() {
f()
fmt.Println("Returned normally from f.")
}
func f() {
defer fmt.Println("Defer in f")
fmt.Println("Calling g.")
g(0)
fmt.Println("Returned normally from g.")
}
func g(i int) {
if i > 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("%v", i))
}
defer fmt.Println("Defer in g", i)
fmt.Println("Printing in g", i)
g(i + 1)
}
Calling g.
Printing in g 0
Printing in g 1
Printing in g 2
Printing in g 3
Panicking!
Defer in g 3
Defer in g 2
Defer in g 1
Defer in g 0
Defer in f
panic: 4
goroutine 1 [running]:
Recover
Recover
● A built-in function from the runtime
● It recovers from a panicking goroutine
● It can only be used in a deferred function
● Calling recover will
○ Return the value given to panic and resume normal execution if the calling goroutine is panicking
○ Return nil and do nothing otherwise
package main
import "fmt"
func main() {
f()
fmt.Println("Returned normally from f.")
}
func f() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
fmt.Println("Calling g.")
g(0)
fmt.Println("Returned normally from g.")
}
func g(i int) {
if i > 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("%v", i))
}
defer fmt.Println("Defer in g", i)
fmt.Println("Printing in g", i)
g(i + 1)
}
Calling g.
Printing in g 0
Printing in g 1
Printing in g 2
Printing in g 3
Panicking!
Defer in g 3
Defer in g 2
Defer in g 1
Defer in g 0
Recovered in f 4
Returned normally from f.
Panic & recover
real use cases
Panic should only be called if
an unrecoverable error occurs
Panic should always be
recovered by the top level
function in order to return an
error (catchable by the caller)
Gin web server
● Panic recovery is implemented in the default middleware
● This recover prevents Gin runtime from crashing because a handler function (defined by the
program that is using Gin framework) panics
○ Handler function is passed to Gin router
○ Client calls the handled endpoint
○ Middleware calls the handling function
○ Handling function panics
○ When returning, handling function acts as a call to panic for the middleware
○ Middleware recovers the panic and throw a 500 HTTP error
JSON package
● unmarshal function handles recovery
● value function calls the type associated
decoding function
● object, array and literal functions reads data
and stores it into given struct
○ literal is the simple function
○ object and array recalls value (indirect
recursion)
● On error, panic is used to unstack calls
Stop sending values to a closed channel
producer
consumer
consumer
consumer
channel
producer
produce
r
close
send
panic
producer
● Multi-producers channel is a problem
○ If a producer closes the channel, others
shouldn’t send (or they’ll panic)
● We can handle it by using multiple ways
○ Share a “done” channel between producers
○ Use a N(1-producer/1-consumer) pattern
○ Recover panic
The problem
1. Create a channel
2. Generate 3 producers
a. After a random waiting time, each producer writes to the chan
b. Then, each producer closes the channel
3. Generate one consumer
a. It consumes the channel until it’s closed
4. Main waits for all the producers and the consumer to exit
The solution
1. Create a channel
2. Generate 3 producers
a. After a random waiting time, each producer writes to the chan
b. Then, each producer closes the channel if nothing has been recovered
3. Generate one consumer
a. It consumes the channel until it’s closed
4. Main waits for all the producers and the consumer to exit
The solution
func main() {
ch := make(chan int)
wg := sync.WaitGroup{}
// Producers
for i := 0; i < 3; i++ {
wg.Add(1)
go func(i int) {
defer func() {
if recover() == nil {
close(ch)
}
fmt.Printf("Producer exited: %dn", i)
wg.Done()
}()
<-time.After(time.Second * time.Duration(rand.Intn(3)))
ch <- i
}(i)
}
// Consumer
wg.Add(1)
go func() {
defer func() {
fmt.Println("Consumer exited")
wg.Done()
}()
for {
select {
case i, ok := <-ch:
if !ok {
return
}
fmt.Printf("Consumed: %dn", i)
}
}
}()
wg.Wait()
}
Thank you!
References
● https://blog.golang.org/defer-panic-and-recover
● https://github.com/gin-gonic/gin
● https://golang.org/src/encoding/json/decode.go?s=3976:4024#L86

More Related Content

What's hot

From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
Dinesh Manajipet
 
Python
PythonPython
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
Open Gurukul
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
Raveen Perera
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
Saraswathi Murugan
 
Nesting of for loops using C++
Nesting of for loops using C++Nesting of for loops using C++
Nesting of for loops using C++
prashant_sainii
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
Arockia Abins
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
Ruby programming introduction
Ruby programming introductionRuby programming introduction
Ruby programming introduction
ASIT Education
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
go-lang
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
Wei-Ning Huang
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
Mohammad Reza Kamalifard
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
Sumit Raj
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
Third session
Third sessionThird session
Third session
AliMohammad155
 
Viii session
Viii sessionViii session
Viii session
AliMohammad155
 
4. python functions
4. python   functions4. python   functions
4. python functions
in4400
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 

What's hot (20)

From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
 
Python
PythonPython
Python
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
Nesting of for loops using C++
Nesting of for loops using C++Nesting of for loops using C++
Nesting of for loops using C++
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Ruby programming introduction
Ruby programming introductionRuby programming introduction
Ruby programming introduction
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
Third session
Third sessionThird session
Third session
 
Viii session
Viii sessionViii session
Viii session
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 

Similar to Defer, Panic, Recover

golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
mustafatahertotanawa1
 
03-fortran.ppt
03-fortran.ppt03-fortran.ppt
03-fortran.ppt
thomashughes837337
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
Ishin Vin
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
Jaehue Jang
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
Hean Hong Leong
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx
cursdjango
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
VijaySharma802
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
RohitYadav830391
 
Functional python
Functional pythonFunctional python
Functional python
Jesué Junior
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
JavaTpoint.Com
 

Similar to Defer, Panic, Recover (20)

golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Function
FunctionFunction
Function
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
03-fortran.ppt
03-fortran.ppt03-fortran.ppt
03-fortran.ppt
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python basic
Python basicPython basic
Python basic
 
08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx08-Iterators-and-Generators.pptx
08-Iterators-and-Generators.pptx
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
Functional python
Functional pythonFunctional python
Functional python
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Defer, Panic, Recover

  • 2. Joris Bonnefoy DevOps @ OVH @devatoria
  • 5. Defer ● A defer statement allows you to execute a function when the calling function returns ● When you call the defer statement, the given function is pushed into a list ● After the surrounding function returned, functions in the list are executed in LIFO order ● Defer is commonly used to improve readability
  • 6. Without defer func CopyFile(dstName, srcName string) (written int64, err error) { src, err := os.Open(srcName) if err != nil { return } dst, err := os.Create(dstName) if err != nil { src.Close() return } written, err = io.Copy(dst, src) dst.Close() src.Close() return }
  • 7. With defer func CopyFile(dstName, srcName string) (written int64, err error) { src, err := os.Open(srcName) if err != nil { return } defer src.Close() dst, err := os.Create(dstName) if err != nil { return } defer dst.Close() return io.Copy(dst, src) }
  • 8. 3 simple defer rules to know
  • 9. 1. A deferred function's arguments are evaluated when the defer statement is evaluated. func main() { i := 0 defer fmt.Println(i) i++ } func main() { i := 0 defer func() { fmt.Println(i) }() i++ } 0 1
  • 10. func main() { for i := 0; i < 4; i++ { defer fmt.Print(i) } } 2. Deferred function calls are executed in Last In First Out order after the surrounding function returns. 3210
  • 11. func f() (i int) { defer func() { i++ }() return 2 } func main() { fmt.Println(f()) } 3. Deferred functions may read and assign to the returning function's named return values. 3
  • 12. Panic
  • 13. Panic ● A built-in function from the runtime ● When the function F calls the panic function ○ It stops the actual execution ○ Deferred functions in F are executed ○ F returns to its caller ○ For the caller, F acts like a call to panic ○ Once all the functions of the panicking goroutine have returned, the program crashes
  • 14. package main import "fmt" func main() { f() fmt.Println("Returned normally from f.") } func f() { defer fmt.Println("Defer in f") fmt.Println("Calling g.") g(0) fmt.Println("Returned normally from g.") } func g(i int) { if i > 3 { fmt.Println("Panicking!") panic(fmt.Sprintf("%v", i)) } defer fmt.Println("Defer in g", i) fmt.Println("Printing in g", i) g(i + 1) } Calling g. Printing in g 0 Printing in g 1 Printing in g 2 Printing in g 3 Panicking! Defer in g 3 Defer in g 2 Defer in g 1 Defer in g 0 Defer in f panic: 4 goroutine 1 [running]:
  • 16. Recover ● A built-in function from the runtime ● It recovers from a panicking goroutine ● It can only be used in a deferred function ● Calling recover will ○ Return the value given to panic and resume normal execution if the calling goroutine is panicking ○ Return nil and do nothing otherwise
  • 17. package main import "fmt" func main() { f() fmt.Println("Returned normally from f.") } func f() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered in f", r) } }() fmt.Println("Calling g.") g(0) fmt.Println("Returned normally from g.") } func g(i int) { if i > 3 { fmt.Println("Panicking!") panic(fmt.Sprintf("%v", i)) } defer fmt.Println("Defer in g", i) fmt.Println("Printing in g", i) g(i + 1) } Calling g. Printing in g 0 Printing in g 1 Printing in g 2 Printing in g 3 Panicking! Defer in g 3 Defer in g 2 Defer in g 1 Defer in g 0 Recovered in f 4 Returned normally from f.
  • 18. Panic & recover real use cases
  • 19. Panic should only be called if an unrecoverable error occurs
  • 20. Panic should always be recovered by the top level function in order to return an error (catchable by the caller)
  • 21. Gin web server ● Panic recovery is implemented in the default middleware ● This recover prevents Gin runtime from crashing because a handler function (defined by the program that is using Gin framework) panics ○ Handler function is passed to Gin router ○ Client calls the handled endpoint ○ Middleware calls the handling function ○ Handling function panics ○ When returning, handling function acts as a call to panic for the middleware ○ Middleware recovers the panic and throw a 500 HTTP error
  • 22. JSON package ● unmarshal function handles recovery ● value function calls the type associated decoding function ● object, array and literal functions reads data and stores it into given struct ○ literal is the simple function ○ object and array recalls value (indirect recursion) ● On error, panic is used to unstack calls
  • 23. Stop sending values to a closed channel producer consumer consumer consumer channel producer produce r close send panic producer ● Multi-producers channel is a problem ○ If a producer closes the channel, others shouldn’t send (or they’ll panic) ● We can handle it by using multiple ways ○ Share a “done” channel between producers ○ Use a N(1-producer/1-consumer) pattern ○ Recover panic
  • 24. The problem 1. Create a channel 2. Generate 3 producers a. After a random waiting time, each producer writes to the chan b. Then, each producer closes the channel 3. Generate one consumer a. It consumes the channel until it’s closed 4. Main waits for all the producers and the consumer to exit
  • 25. The solution 1. Create a channel 2. Generate 3 producers a. After a random waiting time, each producer writes to the chan b. Then, each producer closes the channel if nothing has been recovered 3. Generate one consumer a. It consumes the channel until it’s closed 4. Main waits for all the producers and the consumer to exit
  • 26. The solution func main() { ch := make(chan int) wg := sync.WaitGroup{} // Producers for i := 0; i < 3; i++ { wg.Add(1) go func(i int) { defer func() { if recover() == nil { close(ch) } fmt.Printf("Producer exited: %dn", i) wg.Done() }() <-time.After(time.Second * time.Duration(rand.Intn(3))) ch <- i }(i) } // Consumer wg.Add(1) go func() { defer func() { fmt.Println("Consumer exited") wg.Done() }() for { select { case i, ok := <-ch: if !ok { return } fmt.Printf("Consumed: %dn", i) } } }() wg.Wait() }