Easy error handling in Rails

Let me start by asking what do you think about errors? Many people hate errors and are trying to avoid them as much as possible.

But today I want to show how errors can make your life easier!

Let's say user submitted some form in your application. Where do you check if it's valid? In the controller? Controller's should not be concerned with all that is going on in our models. Should the controller ask a model if data is valid or not? Model should be already checking incoming data.What is you introduce some change deep inside your code, you can't expect to know all the place where it's used!

In Java World (and in others) errors are not actually called "errors", they are called "exceptions" and they can help you to handle exceptional situations. Ruby language has similar exception system. Errors can be raised and rescued.

Let's distinguish between 2 types or errors. 1) Ones that we can actually anticipate and fix. 2) All those bug induced errors, memory errors etc.

First type of error can be fixed by users. Second usually can only be fixed by programmers.

So where should we handle exceptions? Many agree that the most suitable is at system boundaries. We are going to handle it in UI.

First of all, let's define our new class that can be handled.

Second, let's think how we would like our code to look.

Now let's place this method into application controller.

And make it handle optional redirect path.

Let's see how javascript code may look like (jQuery example)

Popular posts from this blog

HTTP server in Ruby 3 - Fibers & Ractors

Next.js: restrict pages to authenticated users

Migration locks for TypeORM