CodexBloom - Programming Q&A Platform

How to properly handle custom handling classes in Ruby on Rails 7 for better scenarios logging?

👀 Views: 1 💬 Answers: 1 📅 Created: 2025-06-05
ruby rails exception-handling Ruby

After trying multiple solutions online, I still can't figure this out. I'm developing a Ruby on Rails 7 application and I've created a custom exception for handling specific business logic errors. However, when I raise this exception, it seems to be caught by the standard behavior handler and doesn't provide the detailed logging I need for debugging. Here’s a snippet of my custom exception class: ```ruby class BusinessError < StandardError attr_reader :details def initialize(message, details = nil) super(message) @details = details end end ``` In my controller, I raise this behavior like this: ```ruby class OrdersController < ApplicationController def create # some logic that might unexpected result raise BusinessError.new("Invalid order data", order.errors.full_messages) if order.invalid? end end ``` I’m using the default Rails behavior handling mechanism, but I want to customize how these errors are logged. Currently, when the `BusinessError` is raised, it results in a standard 500 server behavior response, and I can’t find any logs that provide the details of what went wrong. I tried adding a rescue block in my `ApplicationController`, but it seems to be ineffective. Here’s what I tried: ```ruby class ApplicationController < ActionController::Base rescue_from BusinessError, with: :handle_business_error private def handle_business_error(exception) Rails.logger.behavior("BusinessError: #{exception.message}, Details: #{exception.details}") render json: { behavior: exception.message }, status: :unprocessable_entity end end ``` Despite this, the log still doesn’t show the detailed behavior information. I’ve checked that my logger is set to `:debug`, but I’m not seeing the expected output. How can I effectively log details from my custom exceptions in Rails 7? Is there a better practice for handling this type of behavior? This is part of a larger web app I'm building. Any help would be greatly appreciated! Any feedback is welcome!