Handling a Runtime Error

Is there a way of handling Runtime Errors in order to display a custom message/html element?

My situation, in short –

I have an embedded notebook displaying a WebGL canvas. I want to show a custom error message if this canvas loses context, prompting the visitor to reload the page. To do this, I have an event listener that swaps the canvas for another html element if the context is lost. However, this prompted the question – is it possible to handle a runtime error directly? This might be a terrible idea, I have no clue.

Thanks for your attention!

1 Like

If you want to use Observable’s error handling, then your error messages can only be strings, not HTML elements. Also, Observable’s runtime cannot handle async errors. This, e.g., won’t work:

{
  const canvas = DOM.canvas(600, 400);
  setTimeout(() => {throw Error('Context lost. Reload the page.')}, 1000);
  return canvas;
}

However, you can return a generator that yields your canvas as its first value, and a promise as its last. When an error happens, you reject the promise to let Observable know:

{
  let onError;
  const canvas = DOM.canvas(600, 400);
  const promise = new Promise((_, reject) => { onError = reject});
  setTimeout(() => onError('Context lost. Reload the page.'), 1000);
  
  yield canvas;
  yield promise;
  // Can also be written as:
  // yield* [canvas, promise];
}
2 Likes

By the way, your example is not a JS runtime error in the strictest sense, because Observable’s Runtime will detect that it cannot resolve “undefined_value” even before the cell is executed. That’s why a try / catch has no effect here.

If you want to test or demonstrate “real” runtime errors, try something like this:

{  
  try { window.foo() }
  catch { return "error" }
}
1 Like