Convert Figma logo to code with AI

BetterErrors logobetter_errors

Better error page for Rack apps

6,877
436
6,877
69

Top Related Projects

Rails Console on the Browser.

RSpec for Rails 7+

6,778

A runtime developer console and IRB alternative with powerful introspection capabilities.

55,872

Ruby on Rails

2,809

Rails application preloader

Quick Overview

Better Errors is a Ruby gem that provides a better error page for Rails applications. It replaces the standard Rails error page with a more informative and interactive error page, making it easier to debug and troubleshoot issues in your application.

Pros

  • Provides a more detailed and informative error page, including a stack trace, local variables, and the ability to inspect and interact with the application state.
  • Supports multiple Ruby versions and Rails versions, ensuring compatibility with your project.
  • Integrates well with other popular Ruby libraries, such as Pry and Byebug, for a more seamless debugging experience.
  • Actively maintained and regularly updated, with a responsive community of contributors.

Cons

  • Primarily focused on the development environment, so it may not be suitable for production use.
  • Can potentially expose sensitive information about your application, so it should be used with caution.
  • May not work as expected with certain types of errors or in specific application setups.

Code Examples

Here are a few examples of how to use Better Errors in your Ruby on Rails application:

# config/environments/development.rb
Rails.application.configure do
  config.consider_all_requests_local = true
  config.action_dispatch.show_exceptions = false
  config.better_errors.binding_of_caller = true
  config.better_errors.editor = 'vscode://file/%{file}:%{line}'
end

This configures Better Errors to be enabled in the development environment, and sets the editor integration to work with Visual Studio Code.

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    raise "Oops, something went wrong!"
  end
end

When this controller action raises an exception, Better Errors will display a detailed error page with the stack trace, local variables, and the ability to inspect and interact with the application state.

# Gemfile
gem 'better_errors'
gem 'binding_of_caller'

This adds the Better Errors gem and its dependency, binding_of_caller, to the project's Gemfile.

Getting Started

To get started with Better Errors, follow these steps:

  1. Add the better_errors gem to your project's Gemfile:

    gem 'better_errors'
    
  2. Install the gem by running bundle install in your terminal.

  3. Configure Better Errors to be enabled in your development environment by adding the following code to your config/environments/development.rb file:

    Rails.application.configure do
      config.consider_all_requests_local = true
      config.action_dispatch.show_exceptions = false
      config.better_errors.binding_of_caller = true
      config.better_errors.editor = 'vscode://file/%{file}:%{line}'
    end
    

    This configuration enables Better Errors, allows it to access the binding_of_caller gem, and sets the editor integration to work with Visual Studio Code.

  4. Restart your Rails server, and you should now see the Better Errors error page whenever an exception is raised in your application.

That's it! With these simple steps, you can start using Better Errors to improve your debugging experience in your Ruby on Rails application.

Competitor Comparisons

Rails Console on the Browser.

Pros of rails/web-console

  • Provides a web-based console for interacting with the Rails application, allowing developers to inspect and manipulate the application state directly in the browser.
  • Integrates seamlessly with the Rails framework, making it a natural choice for Rails developers.
  • Offers a user-friendly interface for debugging and troubleshooting.

Cons of rails/web-console

  • Requires the Rails framework, making it less versatile for non-Rails projects.
  • May not provide as much detailed information as BetterErrors/better_errors in certain scenarios.
  • Might have a higher learning curve for developers not familiar with the Rails ecosystem.

Code Comparison

BetterErrors/better_errors:

def better_errors_call_center
  if better_errors_binding_of_caller_available?
    binding.of_caller(1)
  else
    binding
  end
end

rails/web-console:

def console
  if Rails.env.development?
    @console ||= WebConsole::Console.new(
      request,
      session,
      current_user: defined?(current_user) ? current_user : nil
    )
  end
end

RSpec for Rails 7+

Pros of rspec/rspec-rails

  • Comprehensive testing framework: rspec-rails provides a robust and feature-rich testing framework for Ruby on Rails applications, covering a wide range of testing needs.
  • Readability and expressiveness: rspec-rails uses a domain-specific language (DSL) that makes tests more readable and expressive, improving the overall maintainability of the codebase.
  • Extensive ecosystem: The rspec ecosystem includes a large number of third-party libraries and tools that can be integrated to enhance testing capabilities.

Cons of rspec/rspec-rails

  • Steeper learning curve: Compared to the built-in Rails testing framework, rspec-rails has a steeper learning curve, especially for developers new to the Ruby ecosystem.
  • Potential performance impact: The additional layer of abstraction provided by rspec-rails can sometimes result in slower test execution times, especially for large test suites.

Code Comparison

BetterErrors/better_errors:

def handle_exception(env)
  if better_errors_middleware_enabled?(env)
    @exception = env["action_dispatch.exception"]
    @binding_of_caller = env["better_errors.binding_of_caller"]
    @editor = env["better_errors.editor"]
    @application_frames = env["better_errors.application_frames"] || []
    @framework_frames = env["better_errors.framework_frames"] || []
    @hostname = env["SERVER_NAME"]
    @remote_ip = env["action_dispatch.remote_ip"].to_s
    @request_data = env["rack.request.form_hash"] || {}
    @session_data = env["rack.session"] || {}
    @backtrace_cleaner = env["better_errors.backtrace_cleaner"]
    render_error_page(env)
  else
    @exception_wrapper.call(env)
  end
end

rspec/rspec-rails:

RSpec.describe User do
  it "has a name" do
    user = User.new(name: "John Doe")
    expect(user.name).to eq("John Doe")
  end

  it "is not an admin by default" do
    user = User.new(name: "John Doe")
    expect(user).not_to be_admin
  end
end
6,778

A runtime developer console and IRB alternative with powerful introspection capabilities.

Pros of Pry

  • Pry provides a powerful and flexible debugging interface, allowing you to explore and manipulate the state of your application at runtime.
  • Pry offers a wide range of commands and customization options, making it a versatile tool for developers.
  • Pry integrates well with various Ruby frameworks and libraries, providing a seamless debugging experience.

Cons of Pry

  • Pry may have a steeper learning curve compared to BetterErrors, as it offers more advanced features and functionality.
  • Pry may not provide the same level of user-friendliness and simplicity as BetterErrors, especially for beginners or developers who prefer a more straightforward debugging experience.

Code Comparison

Pry:

require 'pry'

def my_function(x, y)
  binding.pry
  result = x + y
  result
end

my_function(2, 3)

BetterErrors:

require 'better_errors'

def my_function(x, y)
  result = x + y
  result
end

my_function(2, 3)
55,872

Ruby on Rails

Pros of rails/rails

  • Comprehensive framework: Rails provides a complete set of tools and features for building web applications, including an ORM, routing, and templating system.
  • Large and active community: Rails has a large and active community of developers, which means there are many resources available for learning and troubleshooting.
  • Extensive ecosystem: Rails has a vast ecosystem of third-party libraries and tools that can be easily integrated into your application.

Cons of rails/rails

  • Complexity: Rails can be complex and overwhelming for beginners, with a steep learning curve.
  • Performance: Rails applications can be slower than other web frameworks, especially for high-traffic websites.

Code Comparison

rails/rails:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :authenticate_user!

  private

  def authenticate_user!
    redirect_to new_user_session_path unless user_signed_in?
  end

  def user_signed_in?
    current_user.present?
  end

  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end
end

BetterErrors/better_errors:

module BetterErrors
  class ErrorPage
    def initialize(exception, env, options = {})
      @exception = exception
      @env = env
      @options = options
    end

    def render
      ERB.new(template).result(binding)
    end

    private

    def template
      File.read(template_path)
    end

    def template_path
      File.expand_path("../templates/main.erb", __FILE__)
    end
  end
end
2,809

Rails application preloader

Pros of Spring

  • Spring provides a faster development workflow by automatically restarting the Rails server when changes are made to the codebase.
  • Spring can significantly reduce the time it takes to boot up the Rails application, especially in larger projects.
  • Spring integrates well with the Rails ecosystem and is widely used by the Rails community.

Cons of Spring

  • Spring can sometimes cause issues with certain gems or configurations, leading to unexpected behavior or errors.
  • Spring's caching mechanism can occasionally cause problems when working with certain database queries or configurations.
  • Spring may not be necessary for smaller Rails projects, and the overhead it adds may not be worth the benefits it provides.

Code Comparison

Better Errors

class BetterErrors::ErrorPage
  def initialize(exception, bindings, options = {})
    @exception = exception
    @bindings = bindings
    @options = options
  end

  def render
    ERB.new(template).result(binding)
  end

  private

  def template
    File.read(template_path)
  end

  def template_path
    File.expand_path("../templates/main.erb", __FILE__)
  end
end

Spring

module Spring
  class Application
    def initialize(app)
      @app = app
    end

    def call(env)
      if env["PATH_INFO"] == "/__spring__/stop"
        stop
        [200, {}, ["OK"]]
      elsif env["PATH_INFO"] == "/__spring__/ping"
        [200, {}, ["OK"]]
      else
        @app.call(env)
      end
    end

    private

    def stop
      Spring.stop
    end
  end
end

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build Status Codacy Badge Test Coverage Gem Version

Better Errors

Better Errors replaces the standard Rails error page with a much better and more useful error page. It is also usable outside of Rails in any Rack app as Rack middleware.

screenshot of Better Errors in action

Features

For screenshots of these features, see the wiki.

  • Full stack trace
  • Source code inspection for all stack frames (with highlighting)
  • Local and instance variable inspection
  • Live shell (REPL) on every stack frame
  • Links directly to the source line in your editor
  • Useful information in non-HTML requests

Installation

Add this to your Gemfile:

group :development do
  gem "better_errors"
  gem "binding_of_caller"
end

binding_of_caller is optional, but is necessary to use Better Errors' advanced features (REPL, local/instance variable inspection, pretty stack frame names).

Note: If you discover that Better Errors isn't working - particularly after upgrading from version 0.5.0 or less - be sure to set config.consider_all_requests_local = true in config/environments/development.rb.

Optional: Set EDITOR

For many reasons outside of Better Errors, you should have the EDITOR environment variable set to your preferred editor. Better Errors, like many other tools, will use that environment variable to show a link that opens your editor to the file and line from the console.

By default the links will open TextMate-protocol links.

To see if your editor is supported or to set up a different editor, see the wiki.

Optional: Set BETTER_ERRORS_INSIDE_FRAME

If your application is running inside of an iframe, or if you have a Content Security Policy that disallows links to other protocols, the editor links will not work.

To work around this set BETTER_ERRORS_INSIDE_FRAME=1 in the environment, and the links will include target=_blank, allowing the link to open regardless of the policy.

This works because it opens the editor from a new browser tab, escaping from the restrictions of your site. Unfortunately it leaves behind an empty tab each time, so only use this if needed.

Security

NOTE: It is critical you put better_errors only in the development section of your Gemfile. Do NOT run better_errors in production, or on Internet-facing hosts.

You will notice that the only machine that gets the Better Errors page is localhost, which means you get the default error page if you are developing on a remote host (or a virtually remote host, such as a Vagrant box). Obviously, the REPL is not something you want to expose to the public, and there may be sensitive information available in the backtrace.

For more information on how to configure access, see the wiki.

Usage

If you're using Rails, there's nothing else you need to do.

Using without Rails.

If you're not using Rails, you need to insert BetterErrors::Middleware into your middleware stack, and optionally set BetterErrors.application_root if you'd like Better Errors to abbreviate filenames within your application.

For instructions for your specific middleware, see the wiki.

Plain text requests

Better Errors will render a plain text error page when the request is an XMLHttpRequest or when the Accept header does not include 'html'.

Unicorn, Puma, and other multi-worker servers

Better Errors works by leaving a lot of context in server process memory. If you're using a web server that runs multiple "workers" it's likely that a second request (as happens when you click on a stack frame) will hit a different worker. That worker won't have the necessary context in memory, and you'll see a Session Expired message.

If this is the case for you, consider turning the number of workers to one (1) in development. Another option would be to use Webrick, Mongrel, Thin, or another single-process server as your rails server, when you are trying to troubleshoot an issue in development.

Changing the link to your editor

Better Errors includes a link to your editor for the file and line of code that is being shown. By default, it uses your environment to determine which editor should be opened. See the wiki for instructions on configuring the editor.

Set maximum variable size for inspector.

# e.g. in config/initializers/better_errors.rb
# This will stop BetterErrors from trying to render larger objects, which can cause
# slow loading times and browser performance problems. Stated size is in characters and refers
# to the length of #inspect's payload for the given object. Please be aware that HTML escaping
# modifies the size of this payload so setting this limit too precisely is not recommended.  
# default value: 100_000
BetterErrors.maximum_variable_inspect_size = 100_000

Ignore inspection of variables with certain classes.

# e.g. in config/initializers/better_errors.rb
# This will stop BetterErrors from trying to inspect objects of these classes, which can cause
# slow loading times and unnecessary database queries. Does not check inheritance chain, use
# strings not constants.
# default value: ['ActionDispatch::Request', 'ActionDispatch::Response']
BetterErrors.ignored_classes = ['ActionDispatch::Request', 'ActionDispatch::Response']

Get in touch!

If you're using better_errors, I'd love to hear from you. Drop me a line and tell me what you think!

Development

After checking out the repo, run bundle install to install the basic dependencies.

You can run the tests with the simplest set of dependencies using:

bundle exec rspec

To run specs for each of the dependency combinations, run:

bundle exec rake test:all

You can run specs for a specific dependency combination using:

BUNDLE_GEMFILE=gemfiles/pry09.gemfile bundle exec rspec

On CI, the specs are run against each gemfile on each supported version of Ruby.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

NPM DownloadsLast 30 Days