ruby-on-rails - 如果我直接命中 'localhost:3000/404'端点,Rails config.exceptions_app无法正常工作

标签 ruby-on-rails ruby error-handling

我正在尝试在Rails API中配置异常(exception)应用程序,以返回404/422/500的自定义JSON,而不是默认错误屏幕。到目前为止,我已经这样做了:

# application.rb
config.exceptions_app = routes

# routes.rb
get '/404', to: 'application#not_found'
get '/422', to: 'application#unacceptable'
get '/500', to: 'application#internal_error'

# application_controller.rb
def not_found
  render json: { error: 'Not found' }, status: :not_found
end
# Likewise, implemented methods for 422 and 500

# development.rb
config.consider_all_requests_local = false

当我通过将GET请求发送到不存在的端点(例如http://localhost:3000/nonexistingroute)在dev服务器中对其进行测试时,它会正确返回在application#not_found中创建的JSON。
在控制台日志中,我看到ActionController::RoutingError (No route matches [GET] "/nonexistingroute")正在处理该错误。

但是,如果我尝试像GET http://localhost:3000/404一样直接测试路由,它将返回200状态,原始Rails错误屏幕显示"The page you were looking for doesn't exist. ... If you are the application owner check the logs for more information."
由于我在控制台日志中什么都看不到,因此我可以想象它根本没有达到我的路线。我想念什么吗?为了使异常(exception)应用程序正常工作,是否需要一些其他设置?

我提到了这些问题,但没有一个回答我的问题:
config.exceptions_app not working in rails
Disable all html exception rendering in rails

先感谢您!

最佳答案

这是因为我没有删除Rails的默认html文件,例如public/404.html。如果您直接命中localhost:3000/404之类的端点,则该应用程序将路由到这些文件。现在,我已经删除了这些文件,所有三个端点都返回带有所需json的404状态。

关于ruby-on-rails - 如果我直接命中 'localhost:3000/404'端点,Rails config.exceptions_app无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750592/

相关文章:

ruby - Ruby 中的运算符和方法

php - Laravel 3、mysql 或 redis down 显示空白屏幕而不是重定向到 500 错误屏幕

javascript - 如何在所有$ http调用中以 Angular 设置$ http.error()?

ruby-on-rails - 为什么 as_json 在 has_one 关联中不返回空对象?

ruby-on-rails - 尝试访问数据库时找不到 gem 'rails'

ruby-on-rails - 如何将换行符转换为 <BR> 标记?

javascript - 是否可以使用JavaScript检测未知的CSS属性或无效的CSS属性值

mysql - 使用 JOIN 时 ActiveRecord 查询中 ORDER 的动态方向

ruby-on-rails - 具有相同模型的 Rails 关联

ruby-on-rails - 服务器发送的事件和 Rails Streaming