SlideShare a Scribd company logo
Error Handling Without Throwing Exceptions
SBTB 2017
Haeley Yao
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 1 / 16
About me
Figure 1: Cat in the yard
3+ years coding in Scala
Passionate about FP
Work in New Product Development(NPD) team in eBay
hayao@ebay.com, @HaeleyYao
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 2 / 16
Projects
Shopbat and mobile app for China market.
Play
Cats
Enumeratum, Scala Scraper
Typesafe config, Typesafe logging
Bigtable
Scalatest, Mockito
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 3 / 16
Side effect
Partiality
Exceptions
Nondeterminism
Dependency injection
Logging
Mutation
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 4 / 16
Throwing Exceptions is partial
1def mean(xs: Seq[Double]): Double =
2if (xs.isEmpty)
3throw new ArithmeticException("mean of empty list!")
4else xs.sum / xs.length
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 5 / 16
Why give up Exceptions
Reduce partiality in program.
Error is defined by type and can be checked at compile time.
Make function composable.
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 6 / 16
Alternatives to throwing Exceptions
Scala: Option, Try, Either
Scalaz: Disjunction, Validation
Scalactic: One, Many(Accumulation)
Cats: Either, Validated
Collection of experiments link
Test link
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 7 / 16
Stacking Future and Either
Future[A] comes up in Scala.
We don’t want to block future, so end up with Future everywhere.
Since Future is asynchronous, any errors need to be captured in there.
Future is designed to handle Throwable.
Composing error handling logic.
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 8 / 16
Simple example on how to use EitherT
1case class EitherT[F[_], A, B](value: F[Either[A, B]])
link
1object SimpleExample {
2sealed trait Error
3case object BadThingHappened extends Error
5def left: EitherT[Future, Error, String] =
6EitherT.fromEither[Future](BadThingHappened.asLeft[String])
8def right: EitherT[Future, Error, String] =
9EitherT.fromEither[Future]("Winning".asRight[Error])
11def failed: EitherT[Future, Error, String] =
12EitherT(
13Future.failed[Either[Error, String]](
14new RuntimeException("FutureFailure ")))
15}
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 9 / 16
Fast-fail error handling
1// Catch fast-fail error.
2def compose: EitherT[Future, Error, String] = {
3for {
4v1 <- left
5v2 <- right
6} yield {
7v2
8}
9}
11// Hanlde result from composition.
12def handle(result: EitherT[Future, Error, String]):
Future[String] = {
13result.value.map {
14case Left(l) => "BadThingHappened"
15case Right(r) => r.toString
16} recover {
17case NonFatal(e) => e.getMessage
18}
19}
20}
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 10 / 16
Designing Error type
1trait AppError
3// Error from external services.
5final case class HTTPError(ip: String, host: String) extends
AppError
6final case class BigTableError(tableName: String) extends
AppError
7final case class TokenError() extends AppError
8final case class UserInfoError(userId: String) extends
AppError
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 11 / 16
Handling error in API call
Validate request header from FE
Validate request body from FE
Call external services
Validate response from external service
Return response to FE
1def validateHeader(headers: Map[String, String]):
Either[AppError, Map[String, String] = ???
2def validateRequest(requestBody: String): Either[AppError,
A] = ???
3def externalService1(header: Map[String, String], body:
String): EitherT[Future, AppError, B] = ???
4def externalServoce2(header: Map[String, String], body:
String): EitherT[Future, AppError, C] = ???
5def validateResponse(response: EitherT[Future, AppError,
C]): EitherT[Future, AppError, C] ???
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 12 / 16
Composition
1// Fast-fail error handling.
2val result = for {
3validatedHeaders <-
EitherT.fromEither[Future](validateHeader(headers))
4validatedBody <-
EitherT.fromEither[Future](validateRequest(requestBody))
5extResult1 <- externalService1(validatedHeaders,
validatedBody)
6extResult2 <- externalService2(validatedHeaders,
extResult1)
7validatedResponse <- validateResponse(extResult2)
8} yield {
9validatedResponse
10}
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 13 / 16
Response for good case and bad case
1val response = (for {
2res <- result.value
3} yield {
4res match {
5case Left(e) =>
InternalServerError(e).as(ContentTypes.JSON)
6case Right(r) => Ok(r).as(ContentTypes.JSON)
7}
8}) recover {
9case NonFatal(e) =>
InternalServerError(e).as(ContentTypes.JSON)
10}
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 14 / 16
Notes for pattern
validateHeader and validateRequest returns Either to keep good
value and bad value.
Transform Either to EitherT for validateHeader and
validateRequest.
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 15 / 16
References
Stacking Future and Either, Herding Cats (link)
Advanced Scala with Cats by Noel Welsh and Dave Gurnell (link)
Chapter 4. Handling errors without exceptions, Functional
Programming in Scala (link)
Designing Fail-Fast Error Handling by Noel Welsh (link)
SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 16 / 16

More Related Content

What's hot

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
Abdul Samee
 
Bitwise Operators in C
Bitwise Operators in CBitwise Operators in C
Bitwise Operators in C
yndaravind
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
Neeru Mittal
 
Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions
Kulachi Hansraj Model School Ashok Vihar
 
(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises
Nico Ludwig
 
Bakery algorithm in operating system
Bakery algorithm in operating systemBakery algorithm in operating system
Bakery algorithm in operating system
Mehdi Hussain
 
Chapter 3 dti2143
Chapter 3 dti2143Chapter 3 dti2143
Chapter 3 dti2143
alish sha
 
Lecture 8 increment_and_decrement_operators
Lecture 8 increment_and_decrement_operatorsLecture 8 increment_and_decrement_operators
Lecture 8 increment_and_decrement_operators
eShikshak
 
C# Fundamentals - Basics of OOPS - Part 2
C# Fundamentals - Basics of OOPS - Part 2C# Fundamentals - Basics of OOPS - Part 2
C# Fundamentals - Basics of OOPS - Part 2
iFour Technolab Pvt. Ltd.
 
Operators
OperatorsOperators
Operators
Kamran
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
programming9
 
Template matching
Template matchingTemplate matching
Template matching
Hasan Ijaz
 
Prefix Postfix
Prefix PostfixPrefix Postfix
Report on c
Report on cReport on c
Report on c
jasmeen kr
 
Bakery algorithm
Bakery algorithmBakery algorithm
Bakery algorithm
Um e Farwa
 
Presentation on Bakery Algorithm
Presentation on Bakery AlgorithmPresentation on Bakery Algorithm
Presentation on Bakery Algorithm
PrimeAsia University
 
P3
P3P3
P3
lksoo
 
Conditional operators
Conditional operatorsConditional operators
Conditional operators
BU
 
Relational operators In C language (By: Shujaat Abbas)
Relational operators In C language (By: Shujaat Abbas)Relational operators In C language (By: Shujaat Abbas)
Relational operators In C language (By: Shujaat Abbas)
Shujaat Abbas
 

What's hot (19)

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
 
Bitwise Operators in C
Bitwise Operators in CBitwise Operators in C
Bitwise Operators in C
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions
 
(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises(4) cpp automatic arrays_pointers_c-strings_exercises
(4) cpp automatic arrays_pointers_c-strings_exercises
 
Bakery algorithm in operating system
Bakery algorithm in operating systemBakery algorithm in operating system
Bakery algorithm in operating system
 
Chapter 3 dti2143
Chapter 3 dti2143Chapter 3 dti2143
Chapter 3 dti2143
 
Lecture 8 increment_and_decrement_operators
Lecture 8 increment_and_decrement_operatorsLecture 8 increment_and_decrement_operators
Lecture 8 increment_and_decrement_operators
 
C# Fundamentals - Basics of OOPS - Part 2
C# Fundamentals - Basics of OOPS - Part 2C# Fundamentals - Basics of OOPS - Part 2
C# Fundamentals - Basics of OOPS - Part 2
 
Operators
OperatorsOperators
Operators
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Template matching
Template matchingTemplate matching
Template matching
 
Prefix Postfix
Prefix PostfixPrefix Postfix
Prefix Postfix
 
Report on c
Report on cReport on c
Report on c
 
Bakery algorithm
Bakery algorithmBakery algorithm
Bakery algorithm
 
Presentation on Bakery Algorithm
Presentation on Bakery AlgorithmPresentation on Bakery Algorithm
Presentation on Bakery Algorithm
 
P3
P3P3
P3
 
Conditional operators
Conditional operatorsConditional operators
Conditional operators
 
Relational operators In C language (By: Shujaat Abbas)
Relational operators In C language (By: Shujaat Abbas)Relational operators In C language (By: Shujaat Abbas)
Relational operators In C language (By: Shujaat Abbas)
 

Similar to Error Handling Without Throwing Exceptions

Functional programming-advantages
Functional programming-advantagesFunctional programming-advantages
Functional programming-advantages
Sergei Winitzki
 
ComputerAssignment7CaseonCentralLimitTheorem.docx
ComputerAssignment7CaseonCentralLimitTheorem.docxComputerAssignment7CaseonCentralLimitTheorem.docx
ComputerAssignment7CaseonCentralLimitTheorem.docx
mccormicknadine86
 
Java Collections
Java CollectionsJava Collections
Java Collections
rithustutorials
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
Tendayi Mawushe
 
Principled Error Handling - Scalapeño
Principled Error Handling - ScalapeñoPrincipled Error Handling - Scalapeño
Principled Error Handling - Scalapeño
Luka Jacobowitz
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
rafbolet0
 
Session 5-exersice
Session 5-exersiceSession 5-exersice
Session 5-exersice
Keroles karam khalil
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
PVS-Studio
 
Test final jav_aaa
Test final jav_aaaTest final jav_aaa
Test final jav_aaa
BagusBudi11
 
APSEC2020 Keynote
APSEC2020 KeynoteAPSEC2020 Keynote
APSEC2020 Keynote
Abhik Roychoudhury
 
random test
random testrandom test
random test
kapilonweb
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Andrzej Jóźwiak
 
Writing tests
Writing testsWriting tests
Writing tests
Jonathan Fine
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8
Giovanni Bassi
 
Java exercise1
Java exercise1Java exercise1
Java exercise1
Jainul Musani
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
Measures for Growth with Firebase Remote Config & Unit Testing Using RxSwift
Measures for Growth with Firebase Remote Config & Unit Testing Using RxSwiftMeasures for Growth with Firebase Remote Config & Unit Testing Using RxSwift
Measures for Growth with Firebase Remote Config & Unit Testing Using RxSwift
Fumiya Sakai
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
 
What every beginning developer should know
What every beginning developer should knowWhat every beginning developer should know
What every beginning developer should know
Andy Lester
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdf
ahmed8651
 

Similar to Error Handling Without Throwing Exceptions (20)

Functional programming-advantages
Functional programming-advantagesFunctional programming-advantages
Functional programming-advantages
 
ComputerAssignment7CaseonCentralLimitTheorem.docx
ComputerAssignment7CaseonCentralLimitTheorem.docxComputerAssignment7CaseonCentralLimitTheorem.docx
ComputerAssignment7CaseonCentralLimitTheorem.docx
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Principled Error Handling - Scalapeño
Principled Error Handling - ScalapeñoPrincipled Error Handling - Scalapeño
Principled Error Handling - Scalapeño
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
 
Session 5-exersice
Session 5-exersiceSession 5-exersice
Session 5-exersice
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
 
Test final jav_aaa
Test final jav_aaaTest final jav_aaa
Test final jav_aaa
 
APSEC2020 Keynote
APSEC2020 KeynoteAPSEC2020 Keynote
APSEC2020 Keynote
 
random test
random testrandom test
random test
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
Writing tests
Writing testsWriting tests
Writing tests
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8
 
Java exercise1
Java exercise1Java exercise1
Java exercise1
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Measures for Growth with Firebase Remote Config & Unit Testing Using RxSwift
Measures for Growth with Firebase Remote Config & Unit Testing Using RxSwiftMeasures for Growth with Firebase Remote Config & Unit Testing Using RxSwift
Measures for Growth with Firebase Remote Config & Unit Testing Using RxSwift
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
What every beginning developer should know
What every beginning developer should knowWhat every beginning developer should know
What every beginning developer should know
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdf
 

Recently uploaded

"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
christinelarrosa
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
DanBrown980551
 

Recently uploaded (20)

"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
 

Error Handling Without Throwing Exceptions

  • 1. Error Handling Without Throwing Exceptions SBTB 2017 Haeley Yao SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 1 / 16
  • 2. About me Figure 1: Cat in the yard 3+ years coding in Scala Passionate about FP Work in New Product Development(NPD) team in eBay hayao@ebay.com, @HaeleyYao SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 2 / 16
  • 3. Projects Shopbat and mobile app for China market. Play Cats Enumeratum, Scala Scraper Typesafe config, Typesafe logging Bigtable Scalatest, Mockito SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 3 / 16
  • 4. Side effect Partiality Exceptions Nondeterminism Dependency injection Logging Mutation SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 4 / 16
  • 5. Throwing Exceptions is partial 1def mean(xs: Seq[Double]): Double = 2if (xs.isEmpty) 3throw new ArithmeticException("mean of empty list!") 4else xs.sum / xs.length SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 5 / 16
  • 6. Why give up Exceptions Reduce partiality in program. Error is defined by type and can be checked at compile time. Make function composable. SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 6 / 16
  • 7. Alternatives to throwing Exceptions Scala: Option, Try, Either Scalaz: Disjunction, Validation Scalactic: One, Many(Accumulation) Cats: Either, Validated Collection of experiments link Test link SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 7 / 16
  • 8. Stacking Future and Either Future[A] comes up in Scala. We don’t want to block future, so end up with Future everywhere. Since Future is asynchronous, any errors need to be captured in there. Future is designed to handle Throwable. Composing error handling logic. SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 8 / 16
  • 9. Simple example on how to use EitherT 1case class EitherT[F[_], A, B](value: F[Either[A, B]]) link 1object SimpleExample { 2sealed trait Error 3case object BadThingHappened extends Error 5def left: EitherT[Future, Error, String] = 6EitherT.fromEither[Future](BadThingHappened.asLeft[String]) 8def right: EitherT[Future, Error, String] = 9EitherT.fromEither[Future]("Winning".asRight[Error]) 11def failed: EitherT[Future, Error, String] = 12EitherT( 13Future.failed[Either[Error, String]]( 14new RuntimeException("FutureFailure "))) 15} SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 9 / 16
  • 10. Fast-fail error handling 1// Catch fast-fail error. 2def compose: EitherT[Future, Error, String] = { 3for { 4v1 <- left 5v2 <- right 6} yield { 7v2 8} 9} 11// Hanlde result from composition. 12def handle(result: EitherT[Future, Error, String]): Future[String] = { 13result.value.map { 14case Left(l) => "BadThingHappened" 15case Right(r) => r.toString 16} recover { 17case NonFatal(e) => e.getMessage 18} 19} 20} SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 10 / 16
  • 11. Designing Error type 1trait AppError 3// Error from external services. 5final case class HTTPError(ip: String, host: String) extends AppError 6final case class BigTableError(tableName: String) extends AppError 7final case class TokenError() extends AppError 8final case class UserInfoError(userId: String) extends AppError SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 11 / 16
  • 12. Handling error in API call Validate request header from FE Validate request body from FE Call external services Validate response from external service Return response to FE 1def validateHeader(headers: Map[String, String]): Either[AppError, Map[String, String] = ??? 2def validateRequest(requestBody: String): Either[AppError, A] = ??? 3def externalService1(header: Map[String, String], body: String): EitherT[Future, AppError, B] = ??? 4def externalServoce2(header: Map[String, String], body: String): EitherT[Future, AppError, C] = ??? 5def validateResponse(response: EitherT[Future, AppError, C]): EitherT[Future, AppError, C] ??? SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 12 / 16
  • 13. Composition 1// Fast-fail error handling. 2val result = for { 3validatedHeaders <- EitherT.fromEither[Future](validateHeader(headers)) 4validatedBody <- EitherT.fromEither[Future](validateRequest(requestBody)) 5extResult1 <- externalService1(validatedHeaders, validatedBody) 6extResult2 <- externalService2(validatedHeaders, extResult1) 7validatedResponse <- validateResponse(extResult2) 8} yield { 9validatedResponse 10} SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 13 / 16
  • 14. Response for good case and bad case 1val response = (for { 2res <- result.value 3} yield { 4res match { 5case Left(e) => InternalServerError(e).as(ContentTypes.JSON) 6case Right(r) => Ok(r).as(ContentTypes.JSON) 7} 8}) recover { 9case NonFatal(e) => InternalServerError(e).as(ContentTypes.JSON) 10} SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 14 / 16
  • 15. Notes for pattern validateHeader and validateRequest returns Either to keep good value and bad value. Transform Either to EitherT for validateHeader and validateRequest. SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 15 / 16
  • 16. References Stacking Future and Either, Herding Cats (link) Advanced Scala with Cats by Noel Welsh and Dave Gurnell (link) Chapter 4. Handling errors without exceptions, Functional Programming in Scala (link) Designing Fail-Fast Error Handling by Noel Welsh (link) SBTB 2017 Error Handling Without Throwing Exceptions Haeley Yao 16 / 16