SlideShare a Scribd company logo
Railway Oriented Programming in Elixir
03/2017
Erlang & Elixir Ireland
@ Zendesk Dublin
@mustafaturan
Summary
Railway Oriented Programming is a clean functional approach for handling errors
- Error Handling in Elixir
- Error Handling with Railway Oriented Programming Approach
- Tip: The bang!
- Questions
Error Handling in Elixir
- Let it crash?
- Try Rescue After blocks
- Try Catch blocks
- Trap exit signal
- Information Tuples with Conditionals
- {:error, …} or {:ok, …}
- If else / case cond do
- Railway Oriented Programming
- WITH Clause (Elixir 1.2)
- Pattern Matching in Function Level
Let it crash?
Ariane 5 flight 501 (1996)
- Engines exploited by a bug
- that was not found in previous models :)
- Do you want to cause an exploit?
Let it crash?
The purpose of ‘Let it Crash!’
- Fresh start
- Generally should not save the state and reload
- Consider it like a restart your computer
- Sometimes save data
- Sometimes not
- Ask this question to yourself:
- Is restarting the process solve my problem, or NOT?
- Samples (it depends!):
- DB connection error, crash, then restart on init
- Retryable
Raise Errors
Simple Raise
iex> raise "Oh no error is coming!"
** (RuntimeError) Oh no error is coming!
Simple Raise with Type
iex> raise ArgumentError, message: "Invalid arg!"
** (ArgumentError) Invalid arg!
Simple Raise with Type
defmodule SampleError do
defexception message: "this is special one"
end
try do
opts
|> Keyword.fetch!(:file_path)
|> File.read!
|> SampleModule.just_do_it!
rescue
e in KeyError -> IO.puts "missing :file_path option"
e in File.Error -> IO.puts "unable to read file"
e in SampleError -> IO.inspect e
end
Rescue Errors
Catch With Pattern Matching in Rescue Clause
try do
opts
|> Keyword.fetch!(:file_path)
rescue
e in KeyError -> IO.puts "missing :file_path option"
after
IO.puts "I will print at both case!"
end
Rescue Errors and After
Need something to execute on both failure and success cases
- Increment metrics ?
Throw and Catch
- Not common
- You can even catch the ‘exit’ signals
- You can pass the value and fetch that value on catch block
try do
for x <- 0..10 do
if x == 2, do: throw(x)
IO.puts(x)
end
catch
x -> "Caught: #{x}"
end
0
1
"Caught: 2"
Trap Exit
def handle_info({:EXIT, _pid, reason}, state),
do: {:stop, reason, state}
def terminate(reason, state) do
# do sth in here
:ok
end
Inside your init() function:
Process.flag(:trap_exit, true)
Inside your module:
Information Tuples
{:ok, some_data}
{:error, some_error_info}
‘If Else’ and ‘Case Cond’ Clauses
- No ‘return’ clause in Elixir
- Simple Checks
- email_exists?(email)
- Complex Controls (Sample: User.Login)
- validate_email_exists()
- validate_email_password_match()
- validate_email_confirmation()
- validate_one_time_password()
- insert_session_token()
If Else
if email_exist?(“sample@sample.com”) do
do_sth()
{:ok, some_value}
else
{:error, %{email: “Not exist”}}
end
Nested Conditions / If Else and Case Cond
maybe_user = fetch_user(email)
case maybe_user do
{:ok, user} ->
case password_match(user, password) do
{:ok, true} ->
case is_confirmed?(user) do
...
end
{:error, msg} ->
{:error, msg}
end
{:error, msg} ->
{:error, msg}
end
Railway Oriented Programming
email_exists? pwd_correct? email_confirm? otp_valid? insert_session
Sample: User login with several checks
resultinput
email_exists? pwd_correct? email_confirm? otp_valid? insert_session
result
input
Railway Oriented Programming with ‘WITH’
‘with’ clause
- Matches patterns with result of the function
- if matches executes next
- Else executes else block
Railway Oriented Programming with ‘WITH’
with {:ok, user} <- fetch_user(email),
{:ok, true} <- password_match(user, password),
{:ok, ...} <- … do
sth()
else
{:error, error} -> handle_me(error)
end
Railway Oriented Programming with
Pattern Matching on Function Level and Pipes
Pattern matching
- on function level
Pipe operator
- to pass result of function to next function's first argument
Railway Oriented Programming with
Pattern Matching on Function Level and Pipes
def process(params) do
params
|> validate_email_exists()
|> validate_email_password_match()
|> validate_email_confirmation()
|> validate_one_time_password()
|> insert_session_token()
end
defp validate_email_password_match({:error, opts}), do: {:error, opts}
defp validate_email_confirmation({:error, opts}), do: {:error, opts}
defp validate_one_time_password({:error, opts}), do: {:error, opts}
defp insert_session_token({:error, opts}), do: {:error, opts}
# You can also create
a macro to create
error catching
functions
automatically
Tip: The bang!
Not a rule BUT:
- In Elixir generally functions has two forms
- without bang!
- some_function(....)
- {:ok, result}
- {:error, “Some message or any type of data”}
- with bang!
- some_function!(...)
- result
- Raise an error
- Elixir ‘bang’ package
- @bang {[list_of_func_name_arg_count_tuples], {CallbackModule, :callback_fn}}
- https://github.com/mustafaturan/bang
Tip: The bang!
defmodule SomeBangModule do
def raise_on_clause({:ok, some_val}),
do: some_val
def raise_on_clause({:error, err}),
do: raise err
end
defmodule OtherModule do
@bang {[do_sth: 1], {SomeBangModule, :raise_on_clause}}
def do_sth({:ok, some_val}) do
if some_val > 0, do: {:ok, “Good!”}, else: {:error, “Invalid”}
end
end
SOURCES
Blog post:
https://medium.com/@mustafaturan/railway-oriented-programmin
g-in-elixir-with-pattern-matching-on-function-level-and-pipelining-
e53972cede98
https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1
Tutor:
https://elixirschool.com/lessons/advanced/error-handling/
Robs’ talk:
https://vimeo.com/113707214
QUESTIONS
THANK YOU

More Related Content

What's hot

Appletjava
AppletjavaAppletjava
Appletjava
DEEPIKA T
 
Asp.net MVC - Course 2
Asp.net MVC - Course 2Asp.net MVC - Course 2
Asp.net MVC - Course 2
erdemergin
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?
satejsahu
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
Phoenix demysitify, with fun
Phoenix demysitify, with funPhoenix demysitify, with fun
Phoenix demysitify, with fun
Tai An Su
 
Java script basic
Java script basicJava script basic
Java script basic
Ravi Bhadauria
 
Test automation in Loris
Test automation in LorisTest automation in Loris
Test automation in Loris
Wasion Wang
 
Econ11 weaving
Econ11 weavingEcon11 weaving
Econ11 weaving
t_ware
 

What's hot (8)

Appletjava
AppletjavaAppletjava
Appletjava
 
Asp.net MVC - Course 2
Asp.net MVC - Course 2Asp.net MVC - Course 2
Asp.net MVC - Course 2
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?
 
Clean Code
Clean CodeClean Code
Clean Code
 
Phoenix demysitify, with fun
Phoenix demysitify, with funPhoenix demysitify, with fun
Phoenix demysitify, with fun
 
Java script basic
Java script basicJava script basic
Java script basic
 
Test automation in Loris
Test automation in LorisTest automation in Loris
Test automation in Loris
 
Econ11 weaving
Econ11 weavingEcon11 weaving
Econ11 weaving
 

Viewers also liked

Anatomy of an elixir process and Actor Communication
Anatomy of an elixir process and Actor CommunicationAnatomy of an elixir process and Actor Communication
Anatomy of an elixir process and Actor Communication
Mustafa TURAN
 
Rolom s4 tarea
Rolom s4 tareaRolom s4 tarea
27 images that prove that we are in danger
27 images that prove that we are in danger27 images that prove that we are in danger
27 images that prove that we are in danger
Dr. Noman F. Qadir
 
Resumo de direito previdenciário 2016 concurso inss
Resumo de direito previdenciário 2016 concurso inssResumo de direito previdenciário 2016 concurso inss
Resumo de direito previdenciário 2016 concurso inss
ecalmont
 
Конституційні обов'язки та права громадян України
Конституційні обов'язки та права громадян УкраїниКонституційні обов'язки та права громадян України
Конституційні обов'язки та права громадян України
Микола Тіяра
 
права ребёнка
права ребёнкаправа ребёнка
права ребёнка
GBDOU23
 
Amplifying your growth through resellers
Amplifying your growth through resellersAmplifying your growth through resellers
Amplifying your growth through resellers
GreenRope
 
презентация к методической работе по теме состав слова
презентация к методической работе по теме состав словапрезентация к методической работе по теме состав слова
презентация к методической работе по теме состав слова
KLLM73
 
Tecno herramientas
Tecno herramientasTecno herramientas
Tecno herramientas
adri algarra camelo
 
презентация п.тичина
презентация п.тичинапрезентация п.тичина
презентация п.тичина
Сергей Колесник
 
Presenting in english
Presenting in englishPresenting in english
Presenting in english
xohiktza escarrega
 
3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...
3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...
3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...
EditorJST
 
4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...
4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...
4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...
EditorJST
 
5. multi level inverter with simplified control strategy for distributed ener...
5. multi level inverter with simplified control strategy for distributed ener...5. multi level inverter with simplified control strategy for distributed ener...
5. multi level inverter with simplified control strategy for distributed ener...
EditorJST
 
6.design fabrication and analysis of tri wheeled electric vehicle (2)
6.design  fabrication and analysis of tri wheeled electric vehicle (2)6.design  fabrication and analysis of tri wheeled electric vehicle (2)
6.design fabrication and analysis of tri wheeled electric vehicle (2)
EditorJST
 

Viewers also liked (15)

Anatomy of an elixir process and Actor Communication
Anatomy of an elixir process and Actor CommunicationAnatomy of an elixir process and Actor Communication
Anatomy of an elixir process and Actor Communication
 
Rolom s4 tarea
Rolom s4 tareaRolom s4 tarea
Rolom s4 tarea
 
27 images that prove that we are in danger
27 images that prove that we are in danger27 images that prove that we are in danger
27 images that prove that we are in danger
 
Resumo de direito previdenciário 2016 concurso inss
Resumo de direito previdenciário 2016 concurso inssResumo de direito previdenciário 2016 concurso inss
Resumo de direito previdenciário 2016 concurso inss
 
Конституційні обов'язки та права громадян України
Конституційні обов'язки та права громадян УкраїниКонституційні обов'язки та права громадян України
Конституційні обов'язки та права громадян України
 
права ребёнка
права ребёнкаправа ребёнка
права ребёнка
 
Amplifying your growth through resellers
Amplifying your growth through resellersAmplifying your growth through resellers
Amplifying your growth through resellers
 
презентация к методической работе по теме состав слова
презентация к методической работе по теме состав словапрезентация к методической работе по теме состав слова
презентация к методической работе по теме состав слова
 
Tecno herramientas
Tecno herramientasTecno herramientas
Tecno herramientas
 
презентация п.тичина
презентация п.тичинапрезентация п.тичина
презентация п.тичина
 
Presenting in english
Presenting in englishPresenting in english
Presenting in english
 
3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...
3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...
3. simulation of 11 level hybrid cascade stack (hcs) inverter with reduced nu...
 
4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...
4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...
4. comparision of pifuzzy techniques for compensation of unbalanced voltages ...
 
5. multi level inverter with simplified control strategy for distributed ener...
5. multi level inverter with simplified control strategy for distributed ener...5. multi level inverter with simplified control strategy for distributed ener...
5. multi level inverter with simplified control strategy for distributed ener...
 
6.design fabrication and analysis of tri wheeled electric vehicle (2)
6.design  fabrication and analysis of tri wheeled electric vehicle (2)6.design  fabrication and analysis of tri wheeled electric vehicle (2)
6.design fabrication and analysis of tri wheeled electric vehicle (2)
 

Similar to Railway Oriented Programming in Elixir

Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
ArnaldoCanelas
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Javatut1
Javatut1 Javatut1
Javatut1
desaigeeta
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
Clay Helberg
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?
Knoldus Inc.
 
Java tutorials
Java tutorialsJava tutorials
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Vijay A Raj
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
noelrap
 
Logical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsLogical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by Professionals
PVS-Studio
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelism
jbugkorea
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 

Similar to Railway Oriented Programming in Elixir (20)

Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Chelberg ptcuser 2010
Chelberg ptcuser 2010Chelberg ptcuser 2010
Chelberg ptcuser 2010
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Logical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsLogical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by Professionals
 
Java 8 - A step closer to Parallelism
Java 8 - A step closer to ParallelismJava 8 - A step closer to Parallelism
Java 8 - A step closer to Parallelism
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 

Recently uploaded

KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 

Recently uploaded (20)

KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 

Railway Oriented Programming in Elixir

  • 1. Railway Oriented Programming in Elixir 03/2017 Erlang & Elixir Ireland @ Zendesk Dublin @mustafaturan
  • 2. Summary Railway Oriented Programming is a clean functional approach for handling errors - Error Handling in Elixir - Error Handling with Railway Oriented Programming Approach - Tip: The bang! - Questions
  • 3. Error Handling in Elixir - Let it crash? - Try Rescue After blocks - Try Catch blocks - Trap exit signal - Information Tuples with Conditionals - {:error, …} or {:ok, …} - If else / case cond do - Railway Oriented Programming - WITH Clause (Elixir 1.2) - Pattern Matching in Function Level
  • 4. Let it crash? Ariane 5 flight 501 (1996) - Engines exploited by a bug - that was not found in previous models :) - Do you want to cause an exploit?
  • 5. Let it crash? The purpose of ‘Let it Crash!’ - Fresh start - Generally should not save the state and reload - Consider it like a restart your computer - Sometimes save data - Sometimes not - Ask this question to yourself: - Is restarting the process solve my problem, or NOT? - Samples (it depends!): - DB connection error, crash, then restart on init - Retryable
  • 6. Raise Errors Simple Raise iex> raise "Oh no error is coming!" ** (RuntimeError) Oh no error is coming! Simple Raise with Type iex> raise ArgumentError, message: "Invalid arg!" ** (ArgumentError) Invalid arg! Simple Raise with Type defmodule SampleError do defexception message: "this is special one" end
  • 7. try do opts |> Keyword.fetch!(:file_path) |> File.read! |> SampleModule.just_do_it! rescue e in KeyError -> IO.puts "missing :file_path option" e in File.Error -> IO.puts "unable to read file" e in SampleError -> IO.inspect e end Rescue Errors Catch With Pattern Matching in Rescue Clause
  • 8. try do opts |> Keyword.fetch!(:file_path) rescue e in KeyError -> IO.puts "missing :file_path option" after IO.puts "I will print at both case!" end Rescue Errors and After Need something to execute on both failure and success cases - Increment metrics ?
  • 9. Throw and Catch - Not common - You can even catch the ‘exit’ signals - You can pass the value and fetch that value on catch block try do for x <- 0..10 do if x == 2, do: throw(x) IO.puts(x) end catch x -> "Caught: #{x}" end 0 1 "Caught: 2"
  • 10. Trap Exit def handle_info({:EXIT, _pid, reason}, state), do: {:stop, reason, state} def terminate(reason, state) do # do sth in here :ok end Inside your init() function: Process.flag(:trap_exit, true) Inside your module:
  • 12. ‘If Else’ and ‘Case Cond’ Clauses - No ‘return’ clause in Elixir - Simple Checks - email_exists?(email) - Complex Controls (Sample: User.Login) - validate_email_exists() - validate_email_password_match() - validate_email_confirmation() - validate_one_time_password() - insert_session_token()
  • 13. If Else if email_exist?(“sample@sample.com”) do do_sth() {:ok, some_value} else {:error, %{email: “Not exist”}} end
  • 14. Nested Conditions / If Else and Case Cond maybe_user = fetch_user(email) case maybe_user do {:ok, user} -> case password_match(user, password) do {:ok, true} -> case is_confirmed?(user) do ... end {:error, msg} -> {:error, msg} end {:error, msg} -> {:error, msg} end
  • 15. Railway Oriented Programming email_exists? pwd_correct? email_confirm? otp_valid? insert_session Sample: User login with several checks resultinput email_exists? pwd_correct? email_confirm? otp_valid? insert_session result input
  • 16. Railway Oriented Programming with ‘WITH’ ‘with’ clause - Matches patterns with result of the function - if matches executes next - Else executes else block
  • 17. Railway Oriented Programming with ‘WITH’ with {:ok, user} <- fetch_user(email), {:ok, true} <- password_match(user, password), {:ok, ...} <- … do sth() else {:error, error} -> handle_me(error) end
  • 18. Railway Oriented Programming with Pattern Matching on Function Level and Pipes Pattern matching - on function level Pipe operator - to pass result of function to next function's first argument
  • 19. Railway Oriented Programming with Pattern Matching on Function Level and Pipes def process(params) do params |> validate_email_exists() |> validate_email_password_match() |> validate_email_confirmation() |> validate_one_time_password() |> insert_session_token() end defp validate_email_password_match({:error, opts}), do: {:error, opts} defp validate_email_confirmation({:error, opts}), do: {:error, opts} defp validate_one_time_password({:error, opts}), do: {:error, opts} defp insert_session_token({:error, opts}), do: {:error, opts} # You can also create a macro to create error catching functions automatically
  • 20. Tip: The bang! Not a rule BUT: - In Elixir generally functions has two forms - without bang! - some_function(....) - {:ok, result} - {:error, “Some message or any type of data”} - with bang! - some_function!(...) - result - Raise an error - Elixir ‘bang’ package - @bang {[list_of_func_name_arg_count_tuples], {CallbackModule, :callback_fn}} - https://github.com/mustafaturan/bang
  • 21. Tip: The bang! defmodule SomeBangModule do def raise_on_clause({:ok, some_val}), do: some_val def raise_on_clause({:error, err}), do: raise err end defmodule OtherModule do @bang {[do_sth: 1], {SomeBangModule, :raise_on_clause}} def do_sth({:ok, some_val}) do if some_val > 0, do: {:ok, “Good!”}, else: {:error, “Invalid”} end end