optional な値と例外
空の std::optional は値なしとして、C++ の例外は Error として届きます。
indexOf は std::optional<int> を返します。文字があればそのインデックスを、optional が空なら値なしを返し、値なしは ?? でデフォルト値に置き換えます。char の引数には 1 文字の文字列を渡します。
parsePercent は std::out_of_range を投げ、main.js はそれを Error として捕捉します。Web では、メッセージは例外の型名とそれに続くテキストです。
試してみる
リストに 'abc' を加えてみましょう。std::stoi が独自の例外を投げます。次に、2 回出てくる文字を探してみましょう。[■]native.h1#pragma once
#include <optional>
#include <string>
// An empty std::optional arrives as no value.
std::optional<int> indexOf(const std::string &text, char letter);
// A C++ exception arrives as an Error you can catch.
int parsePercent(const std::string &text);
[■]main.js2import {
initNative, indexOf, parsePercent,
} from './native/native.h';
await initNative();
const s = await indexOf('crossbind', 's');
const z = await indexOf('crossbind', 'z');
console.log('s is at', s);
console.log('z is at', z ?? 'no place');
for (const text of ['42', '250']) {
try {
console.log(text, 'is', await parsePercent(text));
} catch (error) {
console.log(text, 'throws', error.message);
}
}