In the last content, we demonstrated how to build a simple shopping cart, this time the content is very simple, to add error handling to the shopping cart.
Concurrent processing is an unavoidable problem for web systems, and we mimic a scenario of concurrent conflict:
1. Users enter the shopping cart page, see a total of 5 kinds of merchandise.
2. The administrator maintains a list of items in the background and deletes one of the 5 items.
3. The customer selects the deleted item and adds it to the shopping cart.
In this case, if you do not do any processing will produce an exception, and we have to do is to deal with this exception, to show the user a product does not exist error prompts.
1. First we need to modify the Storecontroller Add_to_cart method, the following is the code for the Add_to_cart method:
def add_to_cart
Product = Product.find (Params[:id])
@cart = Find_cart
@cart. Add_product (product)
R Edirect_to (: Action => ' Display_cart ')
rescue
Logger.error ("Attempt to access invalid product #{params[:id] } ")
flash[:notice] = ' Invalid product '
redirect_to (: Action => ' index ')
end
2. Modify the index.rhtml file in the Rails_apps\depot\app\views\store directory:
Add the following code after the <div id= "main" > This sentence:
<% if @flash [: notice]-%>
<div id= "notice" >
<%= @flash [: notice]%></div>
< % End-%>