Rails makes error handling pretty easy.
In my WoW Quest lookup application, I pass a user inputted numeric to a API call. I would get back a JSON result and then post the result to the results.html.erb page that the user would be routed to.
It was fine, except that if a user inputs a numeric that doesn't map to a valid quest, the user would get a broken page.
So here's what I did. I found that if you send an invalid Quest ID to WoW's API, it returns this JSON:
In my WoW Quest lookup application, I pass a user inputted numeric to a API call. I would get back a JSON result and then post the result to the results.html.erb page that the user would be routed to.
It was fine, except that if a user inputs a numeric that doesn't map to a valid quest, the user would get a broken page.
So here's what I did. I found that if you send an invalid Quest ID to WoW's API, it returns this JSON:
{"status":"nok", "reason": "unable to get quest information."}
So in the controller, I made a modification on the Results action. I added something called "rescue."
Rescue handles errors in Rails.
So now, my results action looks like this, with the added bit in Red text below:
def results @output = JSON.parse(open("http://us.battle.net/api/wow/quest/"+params[:qid]).read) rescue render :template => 'search/error', :status => "nok" end
Basically it's saying this:
If the JSON comes back with a element called "status" and it's equal to the string "nok", then redirect to "view/search/error.html.erb"
That's it. Now if a user inputs a invalid quest id, like 667, it will go to my error.html.erb page... which has some HTML in it to basically say you hit an error, and put a link to go back.
No comments:
Post a Comment