我创建了这段代码来向用户显示特定的错误消息:
application_controller.rb
class ApplicationController < ActionController::Base
rescue_from Exception do |exception|
message = exception.message
message = "default error message" if exception.message.nil?
render :text => message
end
end
room_controller.rb
class RoomController < ApplicationController
def show
@room = Room.find(params[:room_id]) # Can throw 'ActiveRecord::RecordNotFound'
end
def business_method
# something
raise ValidationErros::BusinessException("You cant do this") if something #message "You cant do this" should be shown for user
#...
end
def business_method_2
Room.find(params[:room_id]).do_something
end
end
房间.rb
class Room < ActiveRecord::Base
def do_something
#...
raise ValidationErrors::BusinessException("Invalid state for room") if something #message "Invalid state for room" should be shown for user
#...
end
end
应用程序/模型/错误/validation_errors.rb
module ValidationErrors
class BusinessException < RuntimeError
attr :message
def initialize(message = nil)
@message = message
end
end
end
例子.js
$.ajax({
url: '/room/show/' + roomId,
success: function(data){
//... do something with data
},
error: function(data){
App.notifyError(data) //show dialog with message
}
});
但我不能使用 BusinessException 类。当应引发 BusinessException 时,消息
未初始化的常量 Room::ValidationErrors
显示给用户。
如果我更改此代码:
raise ValidationErrors::BusinessException("Invalid state for room") if something
这样:
raise "Invalid state for room" if something
有用。
此代码的哪些更改适用于带有消息的 BusinessException。我需要这个来rescue_from
在 ApplicationController 中创建具体的方法。
编辑:
感谢您的评论!我的错误是它不知道 ValidationErrors 模块。如何将此模块导入我的班级?
我已经测试将这些行添加到行中:
require 'app/models/errors/validation_errors.rb'
require 'app/models/errors/validation_errors'
但随后引发错误:
cannot load such file -- app/models/errors/validation_errors
解决方案:
https://stackoverflow.com/a/3356843/740394
config.autoload_paths += %W(#{config.root}/app/models/errors)