<s>[INST] import os
import re
from urllib.request import Request, urlopen

def get_image_links(img_url):
    """Return a list of URLs of images within the webpage at img_url."""
    req = Request(img_url, headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req).read().decode('utf-8')
    img_links = re.findall(r'<img[^>]*src="([^"]+)"', webpage)
    return img_links

# Test the function
img_url = "http://example.com"
img_links = get_image_links(img_url)
print(img_links)

def download_images(url_list, folder_path):
    """Download images from the given list of URLs to the specified folder."""
    for url in url_list:
        filename = url.split("/")[-1]
        filepath = os.path.join(folder_path, filename)
        req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        img = urlopen(req).read()
        with open(filepath, 'wb') as file:
            file.write(img)

# Test the function
url_list = img_links
folder_path = "/path/to/folder"
download_images(url_list, folder_path)

The code above has several issues:

1.  Lack of error handling for network requests.
2.  Lack of validation for the folder path.
3.  Does not check if the image link is valid before attempting to download.
4.  Does not handle potential exceptions when writing to the file.

How would I refactor this code to address these issues?[/INST]