You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Haml修改Rails公共目录错误页面?访问/404遇路由错误求解

Hey there! Let's figure out why you're hitting that Routing Error when trying to access localhost:3000/404 after setting up Haml custom error pages. Here are the most common issues and how to fix them:

1. Rails doesn’t serve /404 directly in development mode by default

By default, Rails prioritizes showing detailed debugging info over custom error pages in development. That’s why you’re seeing a Routing Error instead of your Haml page. To change this, update your config/environments/development.rb file:

# Disable detailed local error pages
config.consider_all_requests_local = false
# Enable exception handling to show custom error pages
config.action_dispatch.show_exceptions = true

After making this change, restart your Rails server—this is crucial for the config to take effect.

2. Your Haml error pages aren’t set up correctly for Rails to find them

Rails looks for static HTML files in the public folder by default (like public/404.html). If you’re using Haml, you have two options:

  • Compile Haml to HTML manually: Convert your 404.haml file to 404.html (use the haml command line tool: haml 404.haml public/404.html) and make sure the compiled HTML file lives directly in the public directory.
  • Render Haml templates dynamically: If you want to avoid compiling, set up a dedicated errors controller:
    1. Add these routes to config/routes.rb:
      get '/404', to: 'errors#not_found'
      get '/500', to: 'errors#internal_server_error'
      
    2. Create app/controllers/errors_controller.rb:
      class ErrorsController < ApplicationController
        def not_found
          render status: 404
        end
      
        def internal_server_error
          render status: 500
        end
      
    3. Create Haml templates in app/views/errors/: not_found.html.haml and internal_server_error.html.haml.
3. You forgot to restart your Rails server

I know it’s obvious, but it’s easy to miss! Any changes to config files, routes, or controller setups require a server restart. Stop your current rails s process and start it again.

4. There’s a conflicting route in your routes.rb

Check if you have any other routes that match /404—Rails processes routes top to bottom, so if another route is catching /404 before your error page setup, it’ll trigger the Routing Error. Make sure your error page routes are placed at the bottom of routes.rb to avoid conflicts.

Give these steps a try, and you should be able to see your custom Haml error page when accessing /404!

内容的提问来源于stack exchange,提问作者Johnny Zapata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:13:43