SlideShare a Scribd company logo
Try the Monad!
Streamlining error management in Grails 4
Who am I?
● Luis Muñiz, level 25 JVM Developer
● New Madrileño
● CTO at Sparkers
your entertainment data companion
all things entertainment.
Gaming. Books. Movies.
Streaming. Etc.
Sparkers
Disclaimer(s)
Overview What about Errors?
Why we don’t like how Spring does it?
How we solve it?
How does it affect Grails artifacts?
What about Errors? An error can happen anywhere
We want central error management
Near the point of entry, to provide alternative
response to happy scenario
But this is far away from the error, loss of context
Analyzing the cause is harder
Hard to recover out of context
How Spring does it -
try {
An error can happen anywhere
=> Throw from anywhere
=> Basically GOTO
We want central error management.
Near the point of entry, to provide alternative
response to happy scenario.
=> Exception handlers FTW
=> Error case statically coupled to Exception class
But this is far away from the error, loss of context.
Analyzing the cause is harder.
Hard to recover out of context.
=> You won’t have a clue anyway how to recover from
an exception handler
How Spring does it -
catch {
Complex, static Exception Hierarchies
Catch, log, and re-throw
● Hunt the logs for error causes
● Goodbye consistent error handling
Catch and swallow
● Who knows where this came from anyway?
● Let’s hope for the best
Throw in Transaction rollback for free
● Checked exceptions become a problem
How Spring does it -
catch {
finally { Unchecked Exceptions are not really your friend
Checked exceptions are most certainly not your friend
Most code, unless trivial, is not exception-safe
Expensive to throw
Memory leaks, unclosed files, sockets, partially
written files
Brittle Applications, without intelligent error recovery
Don’t take my word for it
Enough Complaining!
What we need Error Handling next to point of entry
Preserve context
Don’t break flow of control, don’t break function
composition
Allow local or global recovery mechanisms
Our Solution
Error Handling next to point
of entry
Embrace HTTP status codes, even if your
application does not do HTTP
● OK means OK, NOT_FOUND means Not Found,
even if you’re not a web server
● ErrorContext Runtime Exception and factory
methods.
ErrorContext factory methods
ErrorContext is a RuntimeException with:
● code (from HTTP status codes)
● extendedCode (for sub-categories)
● context (for ….. context)
Our Solution
flow of control
function composition
Renounce exceptions and embrace return types
● Never let a function throw an exception
● Enter Javaslang (cough) VAVR’s Try Monad
Our Solution
flow of control
function composition
Try<T>
Parameterized type that represents either:
● Try.Success<T>: successful invocation,
embedding the return value of type T
● Try.Failure<T>: unsuccessful invocation,
embedding a Throwable
Don’t break Flow of Control
Try.of {
}
instead of
try {
} catch() {
}
Don’t break Function Composition
Conditional function
composition with monadic
functions:
● map()
● flatMap()
Functions are only composed if
Try object is a Try.Success,
otherwise the Try.Failure is
returned directly.
or...
Sidenote ;-)
Function Composition is at the heart of intuitively understanding
what Monads are good for (1-slide challenge)
In classical languages:
● Function Composition is “hardcoded” into the semantics and
syntax of the language
● f(g(x)) means: “first call g(x) and feed the result into f()”
⇒ g(x).map(f), in monads, means “compose”
● In Monad Try, composition means: only compose with f if g(x) is
not a Try.Failure
● In Monad Future, composition means: compose with f when
value in g(x) is available
● In Monad List, composition means: apply f to each element of
g(x)
Functional languages with native monads, have nicer syntax for this:
Success and Failure
Failure to Success: Recovery
recover -> map
recoverWith -> flatMap
Success to Failure
Integrated in Grails 4
Our customizations: Layers (Author Resource)
Our customizations: REST Controller
No apparent error handling.
This is done in the ControllerResponses Trait
Our customizations: ControllerResponses (success)
Our customizations: ControllerResponses (failure)
/views/errorContext/_errorContext.gson
Our customizations: Command Object
Our customizations: Façade Service, Transaction Demarcation
Our customizations: Data Service
Key Takeaways
Honest functions The functions announce their return type and promise
not to kick you by throwing exceptions.
In Control Your application can, if needed attempt recovery
close to the source of the error, and still keep the
feature to let errors trickle down into the controller
for handling.
Very simple and
generic Controllers
Thanks to Traits specialized in error handling and
Command objects, the controller methods usually are
reduced to one-liners.
Explicit Transaction
Management
You decide where transactions are rolled back, and
you don’t get rollbacks due to unexpected runtime
exceptions deep in your service layer.
Command Objects
Orchestrate Logic
Your Command objects are no longer dumb Value
Objects but fullfill the function to orchestrate your
use case.
We’re hiring!
https:/
/apply.workable.com/sparkers
Embrace the Monad

More Related Content

What's hot

Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy
Vijay Kumbhar
 
Essential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricksEssential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricks
Kaloyan Raev
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018
Paulo Clavijo
 
Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...
Alberto Lluch Lafuente
 
Switch statement
Switch statementSwitch statement
Switch statement
Patrick John McGee
 
XP in the full stack
XP in the full stackXP in the full stack
XP in the full stack
XP Conference India
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 

What's hot (7)

Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy Test Driven Development Methodology and Philosophy
Test Driven Development Methodology and Philosophy
 
Essential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricksEssential debugging php debugging techniques, tips & tricks
Essential debugging php debugging techniques, tips & tricks
 
TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018TDD and Simple Design Workshop - Session 1 - November 2018
TDD and Simple Design Workshop - Session 1 - November 2018
 
Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...Evaluating the performance of model transformation styles with Maude @ Sympos...
Evaluating the performance of model transformation styles with Maude @ Sympos...
 
Switch statement
Switch statementSwitch statement
Switch statement
 
XP in the full stack
XP in the full stackXP in the full stack
XP in the full stack
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 

Similar to Try the monad!

Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)
Francisco Amores
 
Reconciling Functional Programming and Exceptions
Reconciling Functional Programming and ExceptionsReconciling Functional Programming and Exceptions
Reconciling Functional Programming and Exceptions
Seamus Mc Gonigle
 
Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1Muhamad Hesham
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
Directi Group
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsJaneve George
 
Introduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerIntroduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debugger
Naoto Ono
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
Dr. Syed Hassan Amin
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
Grokking VN
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
Cherimay Batallones
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e prática
PET Computação
 
Best Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentBest Practices in PHP Application Deployment
Best Practices in PHP Application Deployment
Shahar Evron
 
Code quality
Code qualityCode quality
Code quality
44ue
 
Clean code
Clean codeClean code
Clean code
NadiiaVlasenko
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptx
Kalhan Liyanage
 
Functional Programming - Worth the Effort
Functional Programming - Worth the EffortFunctional Programming - Worth the Effort
Functional Programming - Worth the Effort
BoldRadius Solutions
 
Tips about hibernate with spring data jpa
Tips about hibernate with spring data jpaTips about hibernate with spring data jpa
Tips about hibernate with spring data jpa
Thiago Dos Santos Hora
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowKathy Brown
 
Systematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zioSystematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zio
fanf42
 
Structured Software Design
Structured Software DesignStructured Software Design
Structured Software Design
Giorgio Zoppi
 

Similar to Try the monad! (20)

Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)Become Jythonic in FDMEE (KSCOPE15)
Become Jythonic in FDMEE (KSCOPE15)
 
Reconciling Functional Programming and Exceptions
Reconciling Functional Programming and ExceptionsReconciling Functional Programming and Exceptions
Reconciling Functional Programming and Exceptions
 
Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1Design Patterns Summer Course 2010-2011 - Session#1
Design Patterns Summer Course 2010-2011 - Session#1
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Introduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerIntroduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debugger
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
Grokking Techtalk #37: Software design and refactoring
 Grokking Techtalk #37: Software design and refactoring Grokking Techtalk #37: Software design and refactoring
Grokking Techtalk #37: Software design and refactoring
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e prática
 
Best Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentBest Practices in PHP Application Deployment
Best Practices in PHP Application Deployment
 
Code quality
Code qualityCode quality
Code quality
 
Clean code
Clean codeClean code
Clean code
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptx
 
Functional Programming - Worth the Effort
Functional Programming - Worth the EffortFunctional Programming - Worth the Effort
Functional Programming - Worth the Effort
 
Tips about hibernate with spring data jpa
Tips about hibernate with spring data jpaTips about hibernate with spring data jpa
Tips about hibernate with spring data jpa
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To Know
 
Systematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zioSystematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zio
 
Structured Software Design
Structured Software DesignStructured Software Design
Structured Software Design
 

Recently uploaded

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
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
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
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
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 
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
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
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
 
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
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
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
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 

Recently uploaded (20)

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
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
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
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
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 
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 ⚡️
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
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
 
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...
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
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
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 

Try the monad!

  • 1. Try the Monad! Streamlining error management in Grails 4
  • 2. Who am I? ● Luis Muñiz, level 25 JVM Developer ● New Madrileño ● CTO at Sparkers
  • 3. your entertainment data companion all things entertainment. Gaming. Books. Movies. Streaming. Etc. Sparkers
  • 5. Overview What about Errors? Why we don’t like how Spring does it? How we solve it? How does it affect Grails artifacts?
  • 6. What about Errors? An error can happen anywhere We want central error management Near the point of entry, to provide alternative response to happy scenario But this is far away from the error, loss of context Analyzing the cause is harder Hard to recover out of context
  • 7. How Spring does it - try { An error can happen anywhere => Throw from anywhere => Basically GOTO We want central error management. Near the point of entry, to provide alternative response to happy scenario. => Exception handlers FTW => Error case statically coupled to Exception class But this is far away from the error, loss of context. Analyzing the cause is harder. Hard to recover out of context. => You won’t have a clue anyway how to recover from an exception handler
  • 8. How Spring does it - catch { Complex, static Exception Hierarchies Catch, log, and re-throw ● Hunt the logs for error causes ● Goodbye consistent error handling Catch and swallow ● Who knows where this came from anyway? ● Let’s hope for the best Throw in Transaction rollback for free ● Checked exceptions become a problem
  • 9. How Spring does it - catch {
  • 10. finally { Unchecked Exceptions are not really your friend Checked exceptions are most certainly not your friend Most code, unless trivial, is not exception-safe Expensive to throw Memory leaks, unclosed files, sockets, partially written files Brittle Applications, without intelligent error recovery Don’t take my word for it
  • 12. What we need Error Handling next to point of entry Preserve context Don’t break flow of control, don’t break function composition Allow local or global recovery mechanisms
  • 13. Our Solution Error Handling next to point of entry Embrace HTTP status codes, even if your application does not do HTTP ● OK means OK, NOT_FOUND means Not Found, even if you’re not a web server ● ErrorContext Runtime Exception and factory methods.
  • 14. ErrorContext factory methods ErrorContext is a RuntimeException with: ● code (from HTTP status codes) ● extendedCode (for sub-categories) ● context (for ….. context)
  • 15. Our Solution flow of control function composition Renounce exceptions and embrace return types ● Never let a function throw an exception ● Enter Javaslang (cough) VAVR’s Try Monad
  • 16. Our Solution flow of control function composition Try<T> Parameterized type that represents either: ● Try.Success<T>: successful invocation, embedding the return value of type T ● Try.Failure<T>: unsuccessful invocation, embedding a Throwable
  • 17. Don’t break Flow of Control Try.of { } instead of try { } catch() { }
  • 18. Don’t break Function Composition Conditional function composition with monadic functions: ● map() ● flatMap() Functions are only composed if Try object is a Try.Success, otherwise the Try.Failure is returned directly. or...
  • 19. Sidenote ;-) Function Composition is at the heart of intuitively understanding what Monads are good for (1-slide challenge) In classical languages: ● Function Composition is “hardcoded” into the semantics and syntax of the language ● f(g(x)) means: “first call g(x) and feed the result into f()” ⇒ g(x).map(f), in monads, means “compose” ● In Monad Try, composition means: only compose with f if g(x) is not a Try.Failure ● In Monad Future, composition means: compose with f when value in g(x) is available ● In Monad List, composition means: apply f to each element of g(x) Functional languages with native monads, have nicer syntax for this:
  • 21. Failure to Success: Recovery recover -> map recoverWith -> flatMap
  • 24. Our customizations: Layers (Author Resource)
  • 25. Our customizations: REST Controller No apparent error handling. This is done in the ControllerResponses Trait
  • 27. Our customizations: ControllerResponses (failure) /views/errorContext/_errorContext.gson
  • 29. Our customizations: Façade Service, Transaction Demarcation
  • 32. Honest functions The functions announce their return type and promise not to kick you by throwing exceptions. In Control Your application can, if needed attempt recovery close to the source of the error, and still keep the feature to let errors trickle down into the controller for handling. Very simple and generic Controllers Thanks to Traits specialized in error handling and Command objects, the controller methods usually are reduced to one-liners. Explicit Transaction Management You decide where transactions are rolled back, and you don’t get rollbacks due to unexpected runtime exceptions deep in your service layer. Command Objects Orchestrate Logic Your Command objects are no longer dumb Value Objects but fullfill the function to orchestrate your use case.