2

following question

I do have a python script working and doing HTTP requests. Sometimes I get several errors like the http 400. Now I want to log those and interrupt the script from stop working.

 import logging

 date = .strftime().....

 try: 
        script X
 except:
        error = urllib2.HTTPError
        errorcode = error.code
        file = open ("error.txt",'r+')
        file.write("Error Code: %s, date \n", errorcode)
        file.close()
        pass

Is that right? Or did I something wrong. Should I use an If for the HTTP error?

Will this prevent the script from stopping while getting an error -> pass

Thank You!

1
  • 1
    Why cant you just try it yourself? Commented Aug 11, 2015 at 8:08

3 Answers 3

1

Your line saying:

error = urllib2.HTTPError

makes no sense in this context. It is saying error is the urllib2.HTTPError class. That class is used for raising exceptions, you are interested in catching exceptions.

Usually we write:

try: 
    #  http attempt
except urllib2.HTTPError, error:
    errorcode = error.code

This says the type of the exception you are handling, urllib2.HTTPError, and that is what type error will be, or any class object which inherits from urllib2.HTTPError.

It also means you won't handle any other kinds of exceptions. This is a good thing. Only deal with what you can handle and let everything else fly past you.

At the moment your except statement catches every possible exception type. You also throw away the information, so you don't really know what the exception was.

Writing to a file, use with. This makes sure the file is closed properly if there is an exception whilst writing to it. Don't use file as a variable name. You need to interpolate the string format using %:

    with open ("error.txt",'r+') as log:
        log.write("Error Code: %s, date \n" % errorcode)

Okay, code review over.

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

2 Comments

oh right, thank you, my bad. So I will log the error but still use 'pass' for 'going on'
You only need pass if the block would otherwise be empty. See this question.
1

Use python requests library::::

try:
    res = requests.post(url, data, headers=headers, auth=auth)
    if res.status_code == 200 or res.status_code == 201:
        return 'SUCCESS', res.content
    else:
        return 'FAIL', res.status_code
except Exception as e:
    print "Http request failed... %s" % traceback.format_exc()

3 Comments

You should use raise_for_status.
but your method is w/o a error logging. Only printing the error isn't my aim. Furthermore I used the urllib2 instead of request. Should I change it to the request method?
Don't recommend installing a library for a basic question.
0

A better way to structure your code is to use error logging (a feature built into Python):

import logging

logger = logging.getLogger('__name__')

fh = logging.FileHandler('errors.log')
logger.addHandler(fh)

try:
   # something
except urllib2.HttpError, e:
   logger.error(e)

Comments

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.