SlideShare a Scribd company logo
1 of 77
Download to read offline
Moving away from null and
exceptions: An alternative
way of error handling
Mario Fernandez
Andrei Bechet
© 2020 ThoughtWorks
What to expect
© 2020 ThoughtWorks
The two takeaways
© 2020 ThoughtWorks
Let’s stop using null
© 2020 ThoughtWorks
Let’s stop abusing exceptions
© 2020 ThoughtWorks
Some Context
© 2020 ThoughtWorks
JS
API
API
DbLegacy Backend
Big German Corp
Null
© 2020 ThoughtWorks
Did you have a NullPointerException lately
in a production system?
© 2020 ThoughtWorks
© 2020 ThoughtWorks
public static boolean isAdmin(List<Scope> scopes) {
if(scopes == null) {
return false;
}
Scope adminScope = findAdminScope(scopes);
if(adminScope == null) {
return false;
}
return adminScope.isValid();
}
Ad-hoc Error Handling and it pollutes
© 2020 ThoughtWorks
Null values sidestep the type system
© 2020 ThoughtWorks
Runtime instead of compile time
feedback
© 2020 ThoughtWorks
Nullable Types
© 2020 ThoughtWorks
Authorization: Bearer bGciOi...JIUzI1NiIs
fun String.extractToken(): String? = if (startsWith("Bearer"))
split(" ").last()
else
null
header.extractToken()
?.let { token -> doStuff(token) }
What about more
complex flows
© 2020 ThoughtWorks
Get Authorization header
Extract Token
Verify Token
Set Security Context
Null?
request.getHeader(Headers.AUTHORIZATION)
?.let { header ->
header.extractToken()
?.let { jwt ->
verifier.verify(jwt)
?.let { token ->
SecurityContextHolder.getContext().authentication = token
}
}
}
Data Types
A digression about Functional Programming
© 2020 ThoughtWorks
A data type is an abstraction that
encapsulates one reusable coding pattern
© 2020 ThoughtWorks
Think of containers holding your data
© 2020 ThoughtWorks
Provide clear semantics and an interface
to manipulate the data
© 2020 ThoughtWorks
Option Either Validated IO
Examples
© 2020 ThoughtWorks
arrow-kt.io/docs/0.10/datatypes/intro/
© 2020 ThoughtWorks
Option
© 2020 ThoughtWorks
A value that might be absent
© 2020 ThoughtWorks
Option<T>
NoneSome<T>
T
sealed class Option<out T> {
data class Some<out T>(val a: T): Option<T>()
object None: Option<Nothing>()
}
How to use it?
© 2020 ThoughtWorks
fun String.extractToken(): Option<String> = startsWith("Bearer ")
.maybe { split(" ").last() }
when (val token = header.extractToken()) {
is Option.None -> ResponseEntity.status(401).build()
is Option.Some -> ResponseEntity.ok(result.t)
}
A container is not just
a holder of data
© 2020 ThoughtWorks
interface Operations {
fun <A, B> Option<A>.map(f: (A) -> B): Option<B>
fun <A, B> Option<A>.flatMap(f: (A) -> Option<B>): Option<B>
}
Exceptions
The hidden GOTO
© 2020 ThoughtWorks
Did you get a 500 lately in a production
system?
© 2020 ThoughtWorks
… pretty common to throw
© 2020 ThoughtWorks
© 2020 ThoughtWorks
At first Exceptions may sound like
a good idea
© 2020 ThoughtWorks
… but they easily lead to bad decisions
© 2020 ThoughtWorks
Why
© 2020 ThoughtWorks
Easy to ignore or miss
© 2020 ThoughtWorks
Exceptions oftenly end up being used
as flow control
© 2020 ThoughtWorks
Breaks encapsulation
© 2020 ThoughtWorks
© 2020 ThoughtWorks
Controller API clientService layer
Happy path
Error path
Happy path
interface Verifier {
/**
* @param jwt a jwt token
* @return authentication credentials
*/
fun verify(jwt: String): TokenAuthentication
}
© 2020 ThoughtWorks
/**
* Perform the verification against the given Token
*
* @param token to verify.
* @return a verified and decoded JWT.
* @throws AlgorithmMismatchException
* @throws SignatureVerificationException
* @throws TokenExpiredException
* @throws InvalidClaimException
*/
public DecodedJWT verifyByCallingExternalApi(String token);
A typical way of
handling this
© 2020 ThoughtWorks
@ExceptionHandler(JWTVerificationException::class)
fun handleException(exception: JWTVerificationException):
ResponseEntity<ErrorMessage> {
return ResponseEntity
.status(HttpStatus.BAD_GATEWAY)
.body(ErrorMessage.fromException(exception))
}
What is an Exception?
© 2020 ThoughtWorks
A cluster going down 🔥
is an exception
© 2020 ThoughtWorks
Not really an exception
© 2020 ThoughtWorks
As the context grows it becomes harder
to test and reason about
© 2020 ThoughtWorks
Either
© 2020 ThoughtWorks
Two different values depending on the result
of the computation
© 2020 ThoughtWorks
sealed class Either<out L, out R> {
data class Left<out L, out R>(val a: L) : Either<L, R>()
data class Right<out L, out R>(val b: R) : Either<L, R>()
}
How to use it?
© 2020 ThoughtWorks
interface Verifier {
fun verify(token: String): Either<TokenEx, TokenAuth>
}
fun Verifier.unsafeVerify(jwt: String): Either<TokenEx, TokenAuth> = try {
verifyByCallingExternalApi(jwt).right()
} catch (e: JWTVerificationException) {
e.left()
}
An evolving
computation
© 2020 ThoughtWorks
interface Operations {
fun <T, A, B> Either<T, A>.map(f: (A) -> B): Either<T, B>
fun <T, A, B> Either<T, A>.flatMap(f: (A) -> Either<T, B>):
Either<T, B>
}
verifier
.unsafeVerify(jwt)
.map { it.asToken() }
What about more
complex flows
© 2020 ThoughtWorks
Get Authorization header
Extract Token
Verify Token
Set Security Context
Null?
request.getHeader(Headers.AUTHORIZATION)
.toEither()
.flatMap { header ->
header.extractToken()
.flatMap { jwt ->
verifier
.verify(jwt)
.map { token ->
SecurityContextHolder.getContext().authentication = token
}
}
}
Non-Nested Syntax
© 2020 ThoughtWorks
Similar to async/await
© 2020 ThoughtWorks
Either.fx {
val (header) = request.getHeader(Headers.AUTHORIZATION).toEither()
val (jwt) = header.extractToken()
val (token) = verifier.verify(jwt)
SecurityContextHolder.getContext().authentication = token
}
thoughtworks.com/insights/blog/either-data-type-alternative-throwing-exceptions
© 2020 ThoughtWorks
Summary
© 2020 ThoughtWorks
Null and exceptions can lead to flaky,
hard to understand code
© 2020 ThoughtWorks
Let’s stop using null
© 2020 ThoughtWorks
Let’s stop abusing exceptions
© 2020 ThoughtWorks
Continue the
conversation on Slack
© 2020 ThoughtWorks
XConfEurope2020
xconfeurope2020.slack.com
#talk4-alternative-to-null-and-exceptions
#XConfOnline

More Related Content

Similar to Error handling

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 

Similar to Error handling (20)

Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Priming Java for Speed at Market Open
Priming Java for Speed at Market OpenPriming Java for Speed at Market Open
Priming Java for Speed at Market Open
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Ports and Adapters Architecture
Ports and Adapters ArchitecturePorts and Adapters Architecture
Ports and Adapters Architecture
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Online test program generator for RISC-V processors
Online test program generator for RISC-V processorsOnline test program generator for RISC-V processors
Online test program generator for RISC-V processors
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Good code
Good codeGood code
Good code
 
operators.ppt
operators.pptoperators.ppt
operators.ppt
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
Flink Forward San Francisco 2018: Seth Wiesman - "Testing Stateful Streaming ...
Flink Forward San Francisco 2018: Seth Wiesman - "Testing Stateful Streaming ...Flink Forward San Francisco 2018: Seth Wiesman - "Testing Stateful Streaming ...
Flink Forward San Francisco 2018: Seth Wiesman - "Testing Stateful Streaming ...
 
Demystifying The Solid Works Api
Demystifying The Solid Works ApiDemystifying The Solid Works Api
Demystifying The Solid Works Api
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 

More from Thoughtworks

More from Thoughtworks (20)

Design System as a Product
Design System as a ProductDesign System as a Product
Design System as a Product
 
Designers, Developers & Dogs
Designers, Developers & DogsDesigners, Developers & Dogs
Designers, Developers & Dogs
 
Cloud-first for fast innovation
Cloud-first for fast innovationCloud-first for fast innovation
Cloud-first for fast innovation
 
More impact with flexible teams
More impact with flexible teamsMore impact with flexible teams
More impact with flexible teams
 
Culture of Innovation
Culture of InnovationCulture of Innovation
Culture of Innovation
 
Dual-Track Agile
Dual-Track AgileDual-Track Agile
Dual-Track Agile
 
Developer Experience
Developer ExperienceDeveloper Experience
Developer Experience
 
When we design together
When we design togetherWhen we design together
When we design together
 
Hardware is hard(er)
Hardware is hard(er)Hardware is hard(er)
Hardware is hard(er)
 
Customer-centric innovation enabled by cloud
 Customer-centric innovation enabled by cloud Customer-centric innovation enabled by cloud
Customer-centric innovation enabled by cloud
 
Amazon's Culture of Innovation
Amazon's Culture of InnovationAmazon's Culture of Innovation
Amazon's Culture of Innovation
 
Don't cross the Rubicon
Don't cross the RubiconDon't cross the Rubicon
Don't cross the Rubicon
 
Your test coverage is a lie!
Your test coverage is a lie!Your test coverage is a lie!
Your test coverage is a lie!
 
Docker container security
Docker container securityDocker container security
Docker container security
 
Technology Radar Webinar UK - Vol. 22
Technology Radar Webinar UK - Vol. 22Technology Radar Webinar UK - Vol. 22
Technology Radar Webinar UK - Vol. 22
 
A Tribute to Turing
A Tribute to TuringA Tribute to Turing
A Tribute to Turing
 
Rsa maths worked out
Rsa maths worked outRsa maths worked out
Rsa maths worked out
 
Do No Harm: Do Technologists Need a Code of Ethics?
Do No Harm: Do Technologists Need a Code of Ethics?Do No Harm: Do Technologists Need a Code of Ethics?
Do No Harm: Do Technologists Need a Code of Ethics?
 
Machine Learning for Product Managers
Machine Learning for Product ManagersMachine Learning for Product Managers
Machine Learning for Product Managers
 
Making best-in-class security ubiquitous - Why security is no longer just an ...
Making best-in-class security ubiquitous - Why security is no longer just an ...Making best-in-class security ubiquitous - Why security is no longer just an ...
Making best-in-class security ubiquitous - Why security is no longer just an ...
 

Recently uploaded

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Error handling