---
title: "Agile Web Development with Rails 3nd Edition学习笔记-错误处理"
author: "tiny.strimp"
date: "2010-04-26T22:07:46Z"
tags: []
categories: ["编程语言"]
slug: "agile-web-development-with-rails-3nd-edition"
draft: false
lastmod: "2010-04-26T22:07:46Z"
id: 653693
url: "https://seaoflinux.iteye.com/blog/653693"
---

这一部分其实东西很少，这里不做过多的描述，仅仅是记录下来，以便今后查询使用。
以add_to_cart方法为例，当该方法收到一个错误的产品id时，会得到一个ActiveRecord::RecordNotFound错误。对应的包含错误处理的代码如下：

```ruby
def add_to_cart
  product = Product.find(params[:id])
  @cart = find_cart
  @cart.add_product(product)
rescue ActiveRecord::RecordNotFound
  logger.error("Attempt to access invalid product #{params[:id]}" )
  flash[:notice] = "Invalid product"
  redirect_to :action => 'index'
end
```

"rescue"的部分是捕获错误并进行处理的代码。这部分代码的意义描述如下：
第一行：将出错信息写入Log文件
第二行：把出错信息保存到flash对象中。这个对象以哈希的方式保存Error消息。并且这个对像被保存在Session中。我们可以在需要的时候从它里面取出Error消息，显示在用户页面上。
第三行：将页面重定向到index页面。

要将flash显示在用户页面上，可采用如下的方法。
在depot/app/views/layouts/store.html.erb文件的<div id="main">...</div>节点开始部分加入如下代码：

```ruby
<% if flash[:notice] -%>
  <div id="notice"><%= flash[:notice] %>
<% end -%>
```


启动服务，在index页面任意产品处点击“Add to Cart”按钮，显示add_to_cart页面后，把浏览器地址栏中的地址“http://localhost:3000/store/add_to_cart/<id>”修改为“http://localhost:3000/store/add_to_cart/wibble”，点击刷新。你将会看到页面会自动回到index页面，而不是出错页面。同时在index页面中第一个产品之上会看到“Invalid product”的字样。也就是我们在上面代码中写的Error消息的内容。