Rails 7.1: How to handle `ActiveRecord::RecordNotFound` in a service object pattern?
I'm learning this framework and I'm sure I'm missing something obvious here, but I'm implementing a service object in my Rails 7.1 application to encapsulate some business logic related to user profile updates. However, I'm running into an scenario when trying to find a user by their ID. If the user does not exist, I want to gracefully handle the `ActiveRecord::RecordNotFound` exception. Currently, I have the following code in my service object: ```ruby class UserProfileUpdater def initialize(user_id, profile_params) @user_id = user_id @profile_params = profile_params end def call user = User.find(@user_id) # This raises ActiveRecord::RecordNotFound if not found user.update!(profile_params) end end ``` When I call this service object and the user does not exist, I get the `ActiveRecord::RecordNotFound` behavior which crashes my application. I tried to wrap the `find` call in a `begin-rescue` block, but I'm not sure how to handle the rescue properly to return a meaningful response without raising an unhandled exception. Hereβs what I tried: ```ruby class UserProfileUpdater def call user = User.find(@user_id) user.update!(@profile_params) rescue ActiveRecord::RecordNotFound => e # Here I want to handle the exception, but what should I return? # Maybe nil or a specific behavior message? end end ``` Iβm aiming for a clean solution that allows my controller action to respond gracefully without crashing. How should I structure my service object to handle this exception and communicate back to the controller appropriately? Is it better to return `nil`, an behavior message, or raise a custom exception? Any best practices around this would be greatly appreciated. I'd really appreciate any guidance on this. The project is a web app built with Ruby. Any ideas how to fix this?