Created
October 27, 2013 01:52
-
-
Save vaichidrewar/7177054 to your computer and use it in GitHub Desktop.
Exceptions in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
How to raise an exception | |
#Objective: If either player's strategy is something other than "R", "P" or "S" (case-insensitive), the method should raise aRockPaperScissors::NoSuchStrategyError exception. | |
1 class RockPaperScissors | |
2 | |
3 # Exceptions this class can raise: | |
4 class NoSuchStrategyError < StandardError ; end <<<<<<<<<<<<<<< This line defines the type of exception | |
#At appropriate point | |
7 if(/R|S|P/.match(player1[1]) == nil || /R|S|P/.match(player2[1]) == nil) | |
8 raise NoSuchStrategyError , "Strategy must be one of R,P,S" <<<<<< You are raising your custom expection here with custom message | |
9 end | |
#Notice that inside main class—> there is one more class for custom exception and it is inherited from StandardError | |
#Another example | |
#Objective: If there's a network problem-- unfortunately, Ruby's HTTP library can raise many kinds of exceptions-- we convert any of them into a generic OracleOfBacon::NetworkError and re-raise that. | |
7 class OracleOfBacon | |
8 | |
9 class InvalidError < RuntimeError ; end | |
10 class NetworkError < RuntimeError ; end <<<<<<<<<<<< This line defines the type of exception | |
11 class InvalidKeyError < RuntimeError ; end | |
12 | |
36 def find_connections 37 make_uri_from_arguments | |
38 begin | |
39 xml = URI.parse(uri).read | |
40 rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, | |
41 Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, | |
42 Net::ProtocolError => e | |
44 # convert all of these into a generic OracleOfBacon::NetworkError, | |
45 # but keep the original error message | |
46 # your code here | |
43 raise NetworkError <<<<< We are raising our custom exception but since we did not specify our own message original error message is used | |
47 end | |
48 # your code here: create the OracleOfBacon::Response object | |
49 OracleOfBacon::Response.new(xml) | |
50 end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment