---
title: "rails异常(错误)处理"
author: "RunUpwind"
date: "2011-06-22T15:04:01Z"
tags: []
categories: ["编程语言"]
slug: "rails"
draft: false
lastmod: "2011-06-22T15:47:24Z"
id: 1100925
url: "https://runupwind.iteye.com/blog/1100925"
---

方法1：http://www.uedidea.com/rails%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86.html

 

```
def add_to_cart
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound #拦截Product.find()异常
logger.error("Attempt to access invalid product #{params[:id]}") #日志记录
flash[:notice] = "Invalid product" #notice 存放提示信息
redirect_to :action => "index" #跳转到index
end

begin
   @user.destroy
    flash[:notice] = "User #{@user.name} deleted"
rescue Exception => e #如果上面的代码执行发生异常就捕获
   flash[:notice] = e.message
end
```

 

```
begin
  raise ArgumentError, &quot;Bad data&quot;
rescue => err 
  puts err 
ensure
...                       #执行清理工作 
end  
```

 

方法2：around\_filter  

http://hlee.iteye.com/blog/323025

 

```
    around_filter :rescue_record_not_found     
        
    def rescue_record_not_found     
      begin     
        yield     
      rescue ActiveRecord::RecordNotFound     
        render :file => "#{RAILS_ROOT}/public/404.html"    
      end     
    end    
```

 

   hlee 在文中还提到可以这样做：

```
    rescue_from ActiveRecord::RecordNotFound, with => :rescue_record_not_found     
        
    def rescue_record_not_found     
      render :file => "#{RAILS_ROOT}/public/404.html"    
    end    
```

 

方法3：rescue\_action\_in\_public

参考：http://202.199.224.30/post/article/7

```
    def rescue_action_in_public(exception)      
        logger.error("rescue_action_in_public executed")      
        case exception      
        when ActiveRecord::RecordNotFound, ::ActionController::RoutingError,        
          ::ActionController::UnknownAction      
          logger.error("404 displayed")      
          render(:file  => "#{RAILS_ROOT}/public/404.html",      
          :status   => "404 Not Found")      
        else      
          logger.error("500 displayed")      
          render(:file  => "#{RAILS_ROOT}/public/500.html",      
          :status   => "500 Error")      
    #      SystemNotifier.deliver_exception_notification(self, request,        
    #                                                    exception)      
        end      
      end    
```

 

   注意：在不同环境中的配置，生产环境中，默认的配置应该就可以显示效果，但在开发模式下，需要确认/config/environments/development.rb中的

代码

```
config.action_controller.consider_all_requests_local = false   
```

   
如果在本机访问必须增加（app/controllers/application.rb）：

代码

```
def local_request? 
  false 
end  
```

 

错误类型参考：

```
    DEFAULT_RESCUE_RESPONSE = :internal_server_error  
    DEFAULT_RESCUE_RESPONSES = {  
      'ActionController::RoutingError'             => :not_found,  
      'ActionController::UnknownAction'            => :not_found,  
      'ActiveRecord::RecordNotFound'               => :not_found,  
      'ActiveRecord::StaleObjectError'             => :conflict,  
      'ActiveRecord::RecordInvalid'                => :unprocessable_entity,  
      'ActiveRecord::RecordNotSaved'               => :unprocessable_entity,  
      'ActionController::MethodNotAllowed'         => :method_not_allowed,  
      'ActionController::NotImplemented'           => :not_implemented,  
      'ActionController::InvalidAuthenticityToken' => :unprocessable_entity  
    }  
      
    DEFAULT_RESCUE_TEMPLATE = 'diagnostics'  
    DEFAULT_RESCUE_TEMPLATES = {  
      'ActionView::MissingTemplate'       => 'missing_template',  
      'ActionController::RoutingError'    => 'routing_error',  
      'ActionController::UnknownAction'   => 'unknown_action',  
      'ActionView::TemplateError'         => 'template_error'  
    }  
```

 

又看了这篇贴子中的讨论：http://www.iteye.com/topic/708334  
rails的错误处理还需要再研究。