---
title: "Rails3用rescue_from自定义错误页面"
author: "iseesea"
date: "2011-01-04T11:29:13Z"
tags: ["ActiveRecord", "HTML", "Ruby", "XML"]
categories: ["编程语言"]
slug: "rails3-rescue-from"
draft: false
lastmod: "2011-01-04T11:33:43Z"
id: 858500
url: "https://iseesea.iteye.com/blog/858500"
---

很早之前我自定义错误页面都是重写Showexceptions的rescue_action_in_public和rescue_action_locally方法，但是这样做侵入性太强，今天偶尔看到了一个方法：rescue_from的方法，使用方法如下；
rescue_from(*klasses, &block) 
它的第一个参数是出错的类型集合，可以指定多个错误类型或者出错信息，每一项都会调用klass.is_a?(klass);第二个参数是可以带一个block，我们可以使用with来指定:
出错处理是可以继承的，比如底下代码中，如果没有指定错误处理类型的话，就会调同rescue_from 'MyAppError::Base'的出错处理；

```ruby

class ApplicationController < ActionController::Base
rescue_from ActiveRecord::InvalidForeignKey,ActiveRecord::StatementInvalid , :with => :show_fk_errors

    rescue_from 'MyAppError::Base' do |exception|
      render :xml => exception, :status => 500
    end

  protected

  def show_fk_errors(exception)
    render :template => "/errors/fk_error.html.erb",:object=>@exception = exception
  end
end

```


PS：
在ruby文件中如果有中文出错的话可以在文件开头添加

```ruby

#encoding: utf-8
。。。。。。

```

来指定文件编码，如果还出错的话请人工转码吧。。。