/docs/error-handling.md

https://github.com/coast-framework/coast · Markdown · 58 lines · 39 code · 19 blank · 0 comment · 0 complexity · c441957419786e2ac273867bd470f43f MD5 · raw file

  1. # Handling Errors
  2. * [Introduction](#user-content-introduction)
  3. * [Handling Errors](#user-content-handling-errors)
  4. * [Custom Errors](#user-content-custom-errors)
  5. Coast attempts to make clojure exceptions a little nicer by offering two functions: `raise` and `rescue`
  6. In this guide, we learn how clojure exceptions are raised, how to write logic around them and finally creating your own custom exceptions.
  7. ## Introduction
  8. Exceptions are great since they halt the program at a certain stage and make sure everything is correct before proceeding.
  9. Exceptions, especially in clojure, are usually just treated as insane, indecipherable walls of text that tell devs that *something* went wrong, go dive in and find it.
  10. By default, Coast handles all exceptions for you and displays them in a nice format during development. However, you are free to handle exceptions however you want.
  11. ## Handling Errors
  12. Errors can be handled by catching all of them or specifying a name
  13. ### Gotta Catch 'Em All
  14. Here's how `raise` works with one argument
  15. ```clojure
  16. (raise {:message "This is an error with a message key"})
  17. ```
  18. That raises a `clojure.lang.ExceptionInfo` exception with `ex-data`: `{:message "This is an error with a message key"}`
  19. You can `rescue` from this instead of using `try` and `catch` like this:
  20. ```clojure
  21. (let [[_ error] (rescue
  22. (raise {:message "This is an error"}))])
  23. ```
  24. The error variable in the above example now contains `{:message "This is an error"}`
  25. So `rescue` is a macro, which wraps the body in `try` and `catch` and catches any `ExceptionInfo` that comes from `raise`
  26. ### Named Errors
  27. You can rescue individual errors as well
  28. ```clojure
  29. (rescue
  30. (raise {:message "Error!" :custom true})
  31. (raise {:message "Error!"})
  32. :custom)
  33. ```
  34. In the above example, the first error will be caught, the second one will not.
  35. ## Custom Errors
  36. `raise` can also change the "Error has occurred" message as well like this:
  37. ```clojure
  38. (raise "This is a custom error title" {})
  39. ```