Skip to content

Refactor error handling in Collection concern to use exceptions #47

@kanejamison

Description

@kanejamison

Description

The Collection concern currently renders errors directly using render plain: which prevents controllers from customizing error responses and doesn't integrate with application-wide error handling. This violates separation of concerns and makes it impossible to provide JSON API responses or custom error pages.

Current code

lib/bunko/controllers/collection.rb:51-53, 65-67:

unless @post_type
  render plain: "PostType '#{@collection_name}' not found in database. Run: rails bunko:setup[#{@collection_name}]", status: :not_found
  return
end

Problems this causes

  1. Controllers can't customize error responses (JSON, HTML layouts, etc.)
  2. No way to hook into application-wide error handling (rescue_from)
  3. Forces plain text errors - breaks API consistency
  4. Violates separation of concerns (view logic in concern)
  5. Can't use custom error pages or error tracking services
  6. Difficult to test error scenarios

Pros of refactoring

  • Controllers can customize error handling via rescue_from
  • Supports multiple response formats (JSON, HTML, XML)
  • Integrates with error tracking (Sentry, Honeybadger, etc.)
  • Follows Rails conventions for error handling
  • More testable
  • Users can provide custom error pages

Cons of refactoring

  • Requires users to add rescue_from blocks if they want custom handling
  • Default Rails error pages might be less helpful than current messages
  • Need to create custom exception classes

Recommended approach

Create custom exception classes and raise them instead of rendering:

# lib/bunko/errors.rb
module Bunko
  class Error < StandardError; end
  class PostTypeNotFoundError < Error; end
  class CollectionNotFoundError < Error; end
end

# In collection.rb
unless @post_type
  raise Bunko::PostTypeNotFoundError, 
    "PostType '#{@collection_name}' not found. Run: rails bunko:setup[#{@collection_name}]"
end

Users can then handle these in ApplicationController:

rescue_from Bunko::PostTypeNotFoundError, with: :render_404
rescue_from Bunko::CollectionNotFoundError, with: :render_404

Or let Rails handle them with default 500 pages. Could also provide a generator for adding common rescue_from handlers.

References

  • lib/bunko/controllers/collection.rb:51-53
  • lib/bunko/controllers/collection.rb:65-67
  • lib/bunko/controllers/collection.rb:86-88
  • lib/bunko/controllers/collection.rb:100-102
  • lib/bunko/controllers/collection.rb:107-109

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactorStuff we should improve

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions