Handling errors with `download markup from`

@cgrunenberg I would love to see some more error handling in download markup from:

  • add error message of (SSL) errors as text or error classes to HTTP response-class
  • add timeout to download markup from for cases where the server is unresponsive to speed up scripts

Examples (as of 25.12.2025)

Perhaps using your own download function is more useful in this context. In JS, I’d do something like this:

ObjC.import('AppKit');
function loadResource(URL) {
  let resourceString, errorString;
  let keepRunning = true;
  const session = $.NSURLSession.sharedSession;
  const task = 
    session.dataTaskWithURLCompletionHandler($.NSURL.URLWithString(URL), 
    (data, response, error) => {
      if (error.isNil()) {
        if (response.statusCode == 200) {
          resourceString = $.NSString.alloc.initWithDataEncoding(
            data, $.NSUTF8StringEncoding).js;
        } else {
          errorString = 
          `HTTP error ${response.statusCode} while loading "${URL}".`;
        }
      } else {
        errorString = `${error.code} ${error.domain.js}\n${$(error.localizedDescription).js}`;
      }
      keepRunning = false;
    });
  task.resume;
  
  // Wait for task to complete
  const runLoop = $.NSRunLoop.currentRunLoop;
  while (keepRunning) {
    const today = $.NSDate.dateWithTimeIntervalSinceNow(0.1);
    runLoop.runUntilDate(today);
  }
  if (!errorString) {
    return resourceString;
  } else {
    throw new Error(errorString)
  }
}

try {
  const result = loadResource('https://blog.fefe.de/?ts=99063060');
} catch (e) {
  console.log(e);
}

Running this script gives

/* Error: -1200 NSURLErrorDomain
Es ist ein SSL-Fehler aufgetreten. Eine sichere Verbindung zum Server kann nicht hergestellt werden. */

The same thing can be achieved with AppleScript, I think. And this is a more generic approach than using the three separate download… commands in DT.

Where do you see this class?

For a timeout, you’d have to create a session (ie not use sharedSession) with a configuration that sets the timeout. Or, if you’re using the DT commands, wrap them in with timeout. This would not work with the approach taken by the script above, since with timeout works only with commands directed to an app.

1 Like

HTTP status in AppleScript dictionary:

Ah. Yes, didn’t thought about that one! Thanks.

Thanks, I somehow missed that one. And I second your request – just tried downloading from a site with an expired certificate and didn’t get anything useful: HTTP status 0. Given that most sites nowadays should be HTTPS, SSL status information should be added to the class. @cgrunenberg, what do you think?

The next release will add error code and error domain properties to the HTTP response.

1 Like

And the download commands will also use the current AppleScript timeout for the download so that it’s possible to control this via with timeout of x seconds ... end timeout blocks