WRITELOOP

NOTES ON MONADIC ERROR HANDLING - AN ALTERNATIVE TO EXCEPTIONS

Here are some notes on a video from Arjan on Youtube where he presents monadic error handling as a better alternative for exceptions that you could adopt on your python solutions.

2022 August 25
  • The concept is borrowed from functional programming

  • The video used SQLite as example

  • Never use direct string interpolation on SQL queries - that may result on SQL Injection attacks (when they are needed raw, which you should absolutely avoid as much as you can)

  • Python is unique as it uses exceptions for both reporting errors and interpreting the code - so, if you catch all exceptions, that can hide e.g. name errors coming from typos on the code. E.g. the following code will work:

try:
	something
except Exception as ex:
	pass

Because we are catching a general exception here, “something” will be sintatically correct python code, which is dangerous. It raises a “NameError” but it will be “swallowed” by the general exception. So, only handle the errors you have do deal with, and do not hide the other ones using generic exceptions.

  • monad error handling functions are functions that return 2 things: a value, and an error - if one occured. They are used on functional programming, and are a better mechanism for handling errors than exceptions.

  • You must chain all monadic functions, and all of them must behave the same way (have both returns).

  • Each function has a “successful” and “failure” “track”, so that is sometimes referred to as “railway oriented programming”.

  • If you use monadic error handling, there is no hidden control flow like with exceptions. Success and failure are handled explicitly (errors are part of the result of each function, which is provided as input to the next one).

  • Here is a python library that can be used to aid on developing using monadic error handling: https://github.com/dry-python/returns#result-container

NOTE: The original content(s) that inspired this one can be found at:
https://www.youtube.com/watch?v=J-HWmoTKhC8
All copyright and intellectual property of each one belongs to its' original author.