nim-chronos/error_handling.html

373 lines
19 KiB
HTML

<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Errors and exceptions - Chronos</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="open-in.css">
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded "><a href="introduction.html"><strong aria-hidden="true">1.</strong> Introduction</a></li><li class="chapter-item expanded "><a href="examples.html"><strong aria-hidden="true">2.</strong> Examples</a></li><li class="chapter-item expanded affix "><li class="part-title">User guide</li><li class="chapter-item expanded "><a href="concepts.html"><strong aria-hidden="true">3.</strong> Core concepts</a></li><li class="chapter-item expanded "><a href="async_procs.html"><strong aria-hidden="true">4.</strong> async functions</a></li><li class="chapter-item expanded "><a href="error_handling.html" class="active"><strong aria-hidden="true">5.</strong> Errors and exceptions</a></li><li class="chapter-item expanded "><a href="threads.html"><strong aria-hidden="true">6.</strong> Threads</a></li><li class="chapter-item expanded "><a href="tips.html"><strong aria-hidden="true">7.</strong> Tips, tricks and best practices</a></li><li class="chapter-item expanded "><a href="porting.html"><strong aria-hidden="true">8.</strong> Porting code to chronos</a></li><li class="chapter-item expanded "><a href="http_server_middleware.html"><strong aria-hidden="true">9.</strong> HTTP server middleware</a></li><li class="chapter-item expanded affix "><li class="part-title">Developer guide</li><li class="chapter-item expanded "><a href="book.html"><strong aria-hidden="true">10.</strong> Updating this book</a></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Chronos</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/status-im/nim-chronos/" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="errors-and-exceptions"><a class="header" href="#errors-and-exceptions">Errors and exceptions</a></h1>
<ul>
<li><a href="#exceptions">Exceptions</a></li>
<li><a href="#checked-exceptions">Checked exceptions</a></li>
<li><a href="#the-exception-type">The <code>Exception</code> type</a></li>
<li><a href="#compatibility-modes">Compatibility modes</a></li>
</ul>
<h2 id="exceptions"><a class="header" href="#exceptions">Exceptions</a></h2>
<p>Exceptions inheriting from <a href="https://nim-lang.org/docs/system.html#CatchableError"><code>CatchableError</code></a>
interrupt execution of an <code>async</code> procedure. The exception is placed in the
<code>Future.error</code> field while changing the status of the <code>Future</code> to <code>Failed</code>
and callbacks are scheduled.</p>
<p>When a future is read or awaited the exception is re-raised, traversing the
<code>async</code> execution chain until handled.</p>
<pre><code class="language-nim">proc p1() {.async.} =
await sleepAsync(1.seconds)
raise newException(ValueError, &quot;ValueError inherits from CatchableError&quot;)
proc p2() {.async.} =
await sleepAsync(1.seconds)
proc p3() {.async.} =
let
fut1 = p1()
fut2 = p2()
await fut1
echo &quot;unreachable code here&quot;
await fut2
# `waitFor()` would call `Future.read()` unconditionally, which would raise the
# exception in `Future.error`.
let fut3 = p3()
while not(fut3.finished()):
poll()
echo &quot;fut3.state = &quot;, fut3.state # &quot;Failed&quot;
if fut3.failed():
echo &quot;p3() failed: &quot;, fut3.error.name, &quot;: &quot;, fut3.error.msg
# prints &quot;p3() failed: ValueError: ValueError inherits from CatchableError&quot;
</code></pre>
<p>You can put the <code>await</code> in a <code>try</code> block, to deal with that exception sooner:</p>
<pre><code class="language-nim">proc p3() {.async.} =
let
fut1 = p1()
fut2 = p2()
try:
await fut1
except CachableError:
echo &quot;p1() failed: &quot;, fut1.error.name, &quot;: &quot;, fut1.error.msg
echo &quot;reachable code here&quot;
await fut2
</code></pre>
<p>Because <code>chronos</code> ensures that all exceptions are re-routed to the <code>Future</code>,
<code>poll</code> will not itself raise exceptions.</p>
<p><code>poll</code> may still panic / raise <code>Defect</code> if such are raised in user code due to
undefined behavior.</p>
<h2 id="checked-exceptions"><a class="header" href="#checked-exceptions">Checked exceptions</a></h2>
<p>By specifying a <code>raises</code> list to an async procedure, you can check which
exceptions can be raised by it:</p>
<pre><code class="language-nim">proc p1(): Future[void] {.async: (raises: [IOError]).} =
assert not (compiles do: raise newException(ValueError, &quot;uh-uh&quot;))
raise newException(IOError, &quot;works&quot;) # Or any child of IOError
proc p2(): Future[void] {.async, (raises: [IOError]).} =
await p1() # Works, because await knows that p1
# can only raise IOError
</code></pre>
<p>Under the hood, the return type of <code>p1</code> will be rewritten to an internal type
which will convey raises informations to <code>await</code>.</p>
<pre><code class="language-admonition note">Most `async` include `CancelledError` in the list of `raises`, indicating that
the operation they implement might get cancelled resulting in neither value nor
error!
</code></pre>
<p>When using checked exceptions, the <code>Future</code> type is modified to include
<code>raises</code> information - it can be constructed with the <code>Raising</code> helper:</p>
<pre><code class="language-nim"># Create a variable of the type that will be returned by a an async function
# raising `[CancelledError]`:
var fut: Future[int].Raising([CancelledError])
</code></pre>
<pre><code class="language-admonition note">`Raising` creates a specialization of `InternalRaisesFuture` type - as the name
suggests, this is an internal type whose implementation details are likely to
change in future `chronos` versions.
</code></pre>
<h2 id="the-exception-type"><a class="header" href="#the-exception-type">The <code>Exception</code> type</a></h2>
<p>Exceptions deriving from <code>Exception</code> are not caught by default as these may
include <code>Defect</code> and other forms undefined or uncatchable behavior.</p>
<p>Because exception effect tracking is turned on for <code>async</code> functions, this may
sometimes lead to compile errors around forward declarations, methods and
closures as Nim conservatively asssumes that any <code>Exception</code> might be raised
from those.</p>
<p>Make sure to explicitly annotate these with <code>{.raises.}</code>:</p>
<pre><code class="language-nim"># Forward declarations need to explicitly include a raises list:
proc myfunction() {.raises: [ValueError].}
# ... as do `proc` types
type MyClosure = proc() {.raises: [ValueError].}
proc myfunction() =
raise (ref ValueError)(msg: &quot;Implementation here&quot;)
let closure: MyClosure = myfunction
</code></pre>
<h2 id="compatibility-modes"><a class="header" href="#compatibility-modes">Compatibility modes</a></h2>
<p><strong>Individual functions.</strong> For compatibility, <code>async</code> functions can be instructed
to handle <code>Exception</code> as well, specifying <code>handleException: true</code>. Any
<code>Exception</code> that is not a <code>Defect</code> and not a <code>CatchableError</code> will then be
caught and remapped to <code>AsyncExceptionError</code>:</p>
<pre><code class="language-nim">proc raiseException() {.async: (handleException: true, raises: [AsyncExceptionError]).} =
raise (ref Exception)(msg: &quot;Raising Exception is UB&quot;)
proc callRaiseException() {.async: (raises: []).} =
try:
await raiseException()
except AsyncExceptionError as exc:
# The original Exception is available from the `parent` field
echo exc.parent.msg
</code></pre>
<p><strong>Global flag.</strong> This mode can be enabled globally with
<code>-d:chronosHandleException</code> as a help when porting code to <code>chronos</code>. The
behavior in this case will be that:</p>
<ol>
<li>
<p>old-style functions annotated with plain <code>async</code> will behave as if they had
been annotated with <code>async: (handleException: true)</code>.</p>
<p>This is functionally equivalent to
<code>async: (handleException: true, raises: [CatchableError])</code> and will, as
before, remap any <code>Exception</code> that is not <code>Defect</code> into
<code>AsyncExceptionError</code>, while also allowing any <code>CatchableError</code> (including
<code>AsyncExceptionError</code>) to get through without compilation errors.</p>
</li>
<li>
<p>New-style functions with <code>async: (raises: [...])</code> annotations or their own
<code>handleException</code> annotations will not be affected.</p>
</li>
</ol>
<p>The rationale here is to allow one to incrementally introduce exception
annotations and get compiler feedback while not requiring that every bit of
legacy code is updated at once.</p>
<p>This should be used sparingly and with care, however, as global configuration
settings may interfere with libraries that use <code>chronos</code> leading to unexpected
behavior.</p>
<footer id="open-on-gh">Found a bug? <a href="https://github.com/status-im/nim-chronos//edit/master/docs/src/error_handling.md">Edit this page on GitHub.</a></footer>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="async_procs.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="threads.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="async_procs.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="threads.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
</div>
</body>
</html>