2011-02-23 97 views

回答

0

只要無法正確將請求的URL映射到控制器/操作(即路徑與任何路由不匹配),Rails就會顯示404錯誤。任何其他未處理的異常將顯示500錯誤。

1

我在我的應用程序控制器,這樣做:

rescue_from Exception, :with => :handle_error 

def handle_error(exception) 
    if exceptions_to_treat_as_404.include?(exception.class) 
    render_404 
    else 
    raise exception if Rails.env == 'development' 
    body = exception_error_message(exception) 

    #to logger 
    logger.fatal(body) 

    #to email 
    from = '<[email protected]>' 
    recipients = "<[email protected]>" 
    subject = "[ERROR] (#{exception.class}) #{exception.message.inspect}" 
    GenericEmail.create(:subject => subject, :from => from, :recipients => recipients, :body => body) 

    #to PageRequest table 
    log_request(true) 

    #render error message 
    render_500 
    end 
end 


def exceptions_to_treat_as_404 
    exceptions = [AbstractController::ActionNotFound, 
     ActiveRecord::RecordNotFound, 
       ActionController::UnknownController, 
       URI::InvalidURIError, 
       ActionController::UnknownAction] 
    exceptions << ActionController::RoutingError if ActionController.const_defined?(:RoutingError) 
    exceptions 
end