0

ユーザーに特定のエラー メッセージを表示するために、次のコードを作成しました。

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 で機能しますか。rescue_fromApplicationController で特定のメソッドを作成するには、これが必要です。

編集:

コメントありがとうございます!私のエラーは、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)
4

1 に答える 1

0
raise ::ValidationErrors::BusinessException("Invalid state for room")
于 2012-07-05T04:23:09.757 に答える