仅向用户显示例外消息

时间:2012-07-05 01:02:16

标签: ruby-on-rails ruby

我已创建此代码以向用户显示特定错误消息:

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

room.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

example.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和消息的更改有效。我需要这个 在ApplicationController中创建特定的rescue_from方法。

修改

感谢您的评论! 我的错误是它不知道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)

1 个答案:

答案 0 :(得分:0)

raise ::ValidationErrors::BusinessException("Invalid state for room")