本篇針對購物車加入錯誤處理機制,模擬併發情境下商品被刪除後使用者仍嘗試加入購物車的情況,展示 Rails 如何優雅處理例外並回饋使用者。
若無例外處理,將拋出 ActiveRecord::RecordNotFound 導致 500 錯誤。我們透過 rescue 捕捉例外,記錄日誌並以 flash 顯示友善提示。
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
redirect_to(:action => 'display_cart')
rescue
logger.error("Attempt to access invalid product #{params[:id]}")
flash[:notice] = 'Invalid product'
redirect_to(:action => 'index')
end
logger.error 將錯誤寫入 log/development.log,flash[:notice] 則在下一個請求中可取得訊息。
在 index.rhtml 的 <div id="main"> 後加入:
<% if @flash[:notice] -%> <div id="notice"><%= @flash[:notice] %></div> <% end -%>
模擬上述步驟即可看到「Invalid product」提示(如下圖)。

修改 display_cart,當購物車為空時導向首頁並提示:
def display_cart
@cart = find_cart
@items = @cart.items
if @items.empty?
flash[:notice] = "Your cart is currently empty"
redirect_to(:action => 'index')
end
end
使用者未選商品直接點擊「Show My Cart」時將看到提示(如下圖)。
