SlideShare a Scribd company logo
1 of 34
Download to read offline
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 & tricksKaloyan 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 2018Paulo 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
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan 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 ExceptionsSeamus 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 ParadigmsDirecti 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 debuggerNaoto 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 ProcessDr. 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 refactoringGrokking VN
 
MapReduce: teoria e prática
MapReduce: teoria e práticaMapReduce: teoria e prática
MapReduce: teoria e práticaPET Computação
 
Best Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentBest Practices in PHP Application Deployment
Best Practices in PHP Application DeploymentShahar Evron
 
Code quality
Code qualityCode quality
Code quality44ue
 
Cucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxCucumber for automated acceptance testing.pptx
Cucumber for automated acceptance testing.pptxKalhan Liyanage
 
Functional Programming - Worth the Effort
Functional Programming - Worth the EffortFunctional Programming - Worth the Effort
Functional Programming - Worth the EffortBoldRadius 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 jpaThiago 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 ziofanf42
 
Structured Software Design
Structured Software DesignStructured Software Design
Structured Software DesignGiorgio 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

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 

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.