我正在尝试在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/