32

I want to grab the HTTP status code once it raises a URLError exception:

I tried this but didn't help:

except URLError, e:
    logger.warning( 'It seems like the server is down. Code:' + str(e.code) )
1
  • 1
    Strange. Can you paste the code you use for opening the url? Commented Aug 12, 2010 at 8:07

2 Answers 2

65

You shouldn't check for a status code after catching URLError, since that exception can be raised in situations where there's no HTTP status code available, for example when you're getting connection refused errors.

Use HTTPError to check for HTTP specific errors, and then use URLError to check for other problems:

try:
    urllib2.urlopen(url)
except urllib2.HTTPError, e:
    print e.code
except urllib2.URLError, e:
    print e.args

Of course, you'll probably want to do something more clever than just printing the error codes, but you get the idea.

Sign up to request clarification or add additional context in comments.

1 Comment

To be 100% safe, you might also want to check for ValueError as urllib2.urlopen will throw ValueError exception when the url entered is invalid or blank.
2

Not sure why you are getting this error. If you are using urllib2 this should help:

import urllib2
from urllib2 import URLError

try:
    urllib2.urlopen(url)
except URLError, e:
    print e.code

1 Comment

'URLError' object has no attribute 'code'. It is better to use e.reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.