Way to check URL & response

I’m testing out TidByt development, and have a configurable text where you enter an image URL in a text field. A couple of questions:

  1. Is there a way to check for a valid URL before calling http.get(URL)? Otherwise I get an error Error in get. I’d like a way to catch it.
  2. Is there a way to check if the response from a URL is an image?

Say I have a URL that does not produce an image:

url = "<non_image_url>"

res = http.get(url) # If invalid URL - Error in get: Get <invalid_url>: dial tcp <invalid_url>: connect: connection refused
img = res.body() 

return render.Root(
    child = render.Padding(
        child = render.Image(src = img), # Error in Image: decoding image data: image: unknown format
        pad = 1,
    ),
)

Is there a way for me to check img is a valid image before calling render.Image?

UPDATE: Checking via res.headings content-type seems to be something I can do. Let me know if there’s a better way.

You could validate the URL format using the regular expressions module.

As for the image content, I’d say checking the content-type header is the best option.

Startlark has no try/catch blocks, so there’s no easy way to do error handling apart from checking everything.

Thanks for the reply!

Checking the content-type is what I ended up doing. I also tried checking res.encoding but it’s always empty.

To bad there’s no try/catch or way to check URL’s are valid.

You can check the validity of URLs typed by the users with regular expressions as I mentioned in the previous comment. But of course you won’t know if the URL is real and actually returns something until you call it. :wink:

1 Like