Errors and the person's controls
Your view sends messages and requests actions on behalf of a person who stays in control of it. They accepted your view, can switch back to the UNaIVERSE view at any time and decide which features of the browser your view may use. Moreover a message can fail to be delivered, the rules can refuse an action at this moment and your page can be opened outside the webapp where there is no world. Each of these cases reaches your code as a result or as an error code. The patterns on this page turn either one into a message for the person.
Two kinds of "no"
The kit reports a negative outcome in two ways and your code must handle both:
- A result. The call ran and its promise resolves with a string that names the outcome (
sendresolves'sent','failed'or'not-allowed'). Results are ordinary outcomes of a world with rules and you check them withif. - An error. The call could not run and its promise rejects with an
Errorwhosecodeis a string such as'failed','declined'or'no-host'. Errors come from the webapp or from a choice of the person and you catch them withtry/catch.
try {
const result = await world.send('hello'); // a result: 'sent', 'failed' or 'not-allowed'
if (result === 'not-allowed') showNotYourTurn();
} catch (error) {
showProblem(error.code); // an error: 'failed', 'too-big', ...
}When connecting
connectToHost() resolves with the world or rejects with one of two codes:
| Code | Why | What to do |
|---|---|---|
'no-host' | Your page is not inside the webapp (it was opened alone in a tab) or the webapp did not answer in time. | Show a short message with a link to the world in UNaIVERSE. During development use a fake world. |
'unsupported' | The webapp does not accept the version of your kit. | Use the kit from this site or from its GitHub repository (Installation). Both speak version 1 of the protocol of the webapp. |
Some people open the address of your view directly from search results, from a shared link or from the menu of your own site. Show them a message instead of an empty page:
try {
const world = await connectToHost();
start(world);
} catch (error) {
const message = document.createElement('p');
message.textContent = error.code === 'no-host'
? 'This page is the view of a world in UNaIVERSE. Open the world in UNaIVERSE to use it.'
: `This view cannot start (${error.code}).`;
document.body.append(message);
}The recipe Show a message outside the webapp has a complete version.
Deep dive: 'no-host' inside the webapp
connectToHost() waits timeoutMs (5 seconds by default) for the webapp to answer and then rejects with 'no-host'. The webapp usually answers in a fraction of a second. If your view runs on slow phones and you see 'no-host' inside the webapp, raise the timeout with connectToHost({ timeoutMs: 15000 }) without going past the 20 seconds that the webapp gives your view (below).
The results of acting
send(value), message.answer(values) and message.retry() resolve with a SendResult:
| Result | Means | What to do |
|---|---|---|
'sent' | Delivered. | Nothing. The world changes and subscribe renders the change. |
'failed' | Not delivered. The message is in world.messages with status: 'failed'. | Show it as failed with a Retry button that calls message.retry(). |
'not-allowed' | The world does not accept it now for one of four reasons: (1) world.canSend is false (not the turn of the person or the world is offline), (2) the message is empty or the agent is unreachable, (3) the question was already answered or values names no field of its form or (4) the message had not failed (for retry). | Prevent it by disabling the button while world.canSend is false or explain the reason. |
act(name, args) resolves with one of these results:
| Result | Means | What to do |
|---|---|---|
'requested' | The rules took the request. | Nothing. The world changes when the action happens. |
'refused' | The rules did not accept it (the action is listed but does not take requests at this moment) or did not answer within 10 seconds. | Tell the person. The now of the world usually gives the reason. |
'not-allowed' | name is not in world.now.actions now. | Draw your buttons from world.now.actions and it never happens. |
The errors of calls
Any call that runs through the webapp can reject with one of these codes:
| Code | From | Why | What to do |
|---|---|---|---|
'too-big' | send with a file | The file is over 20 MB. Nothing was sent. | Show the limit and let the person pick a smaller file. |
'declined' | askFor | The person refused. | Offer an alternative. Do not ask again because every later call rejects in the same way while your view is open. |
'unavailable' | askFor, identity, openProfile | The webapp has nothing to give (no features to allow, no me, no profile card). | Keep the view usable without it and never retry in a loop. |
'not-allowed-verb' | setPath, askFor, identity, openProfile, send with a file | The webapp is older than your kit and does not know this call. | Rare. Continue without what the call gives (the address, the feature, me, the profile card or the file). |
'failed' | any | Anything else went wrong in the webapp (for example an answer to a message that no longer exists). | Tell the person that it did not work and let them try again. |
One place for all of it
Most views need one small function that runs an action for the person and turns every outcome into a message. In the example below the first letter fails because the fake world has failNext. The retry gets through and the world offers the stamp without the parcel.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world to build with. Its first message fails (failNext), to show a retry.
const office = {
name: 'Post office',
now: { text: 'Open', actions: [{ name: 'stamp', text: 'Buy a stamp' }] },
failNext: true,
onMessage: (message) => `Delivered: ${message.text}`,
onAction: () => 'Here is your stamp.',
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: office } });
const [status, setStatus] = useState('');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Does one thing for the person, and says how it went, in words.
async function attempt(run) {
try {
const result = await run();
if (result === 'sent' || result === 'requested') setStatus('Done.');
else if (result === 'failed') setStatus('Not delivered. You can retry.');
else if (result === 'refused') setStatus('The world did not take it.');
else setStatus('Not possible right now.'); // 'not-allowed'
} catch (problem) {
// Thrown: the webapp could not do it, and the code says why.
if (problem.code === 'failed') setStatus('Something went wrong in the webapp. Try again.');
else setStatus(`Something went wrong (${problem.code}).`);
}
}
const failed = world.messages.find((message) => message.status === 'failed');
const lines = world.messages.filter((message) => !message.fromMe).map((message) => message.text);
return (
<>
<div>
<button onClick={() => attempt(() => world.send('letter'))}>Send a letter</button>
<button onClick={() => attempt(() => world.act('stamp'))}>Buy a stamp</button>
{/* Not offered now: 'not-allowed'. */}
<button onClick={() => attempt(() => world.act('parcel'))}>Buy a parcel</button>
{failed && <button onClick={() => attempt(() => failed.retry())}>Retry</button>}
</div>
<p>{status}</p>
<div>{lines.join(' · ')}</div>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with. Its first message fails (failNext), to show a retry.
const office = {
name: 'Post office',
now: { text: 'Open', actions: [{ name: 'stamp', text: 'Buy a stamp' }] },
failNext: true,
onMessage: (message) => `Delivered: ${message.text}`,
onAction: () => 'Here is your stamp.',
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: office } });
const status = document.createElement('p');
const actions = document.createElement('div');
const list = document.createElement('div');
document.body.append(actions, status, list);
// Does one thing for the person, and says how it went, in words.
async function attempt(run) {
try {
const result = await run();
if (result === 'sent' || result === 'requested') status.textContent = 'Done.';
else if (result === 'failed') status.textContent = 'Not delivered. You can retry.';
else if (result === 'refused') status.textContent = 'The world did not take it.';
else status.textContent = 'Not possible right now.'; // 'not-allowed'
} catch (error) {
// Thrown: the webapp could not do it, and the code says why.
if (error.code === 'failed') status.textContent = 'Something went wrong in the webapp. Try again.';
else status.textContent = `Something went wrong (${error.code}).`;
}
}
function button(label, run) {
const element = document.createElement('button');
element.textContent = label;
element.onclick = () => attempt(run);
return element;
}
world.subscribe((node) => {
const failed = node.messages.find((message) => message.status === 'failed');
actions.replaceChildren(
button('Send a letter', () => world.send('letter')),
button('Buy a stamp', () => world.act('stamp')),
button('Buy a parcel', () => world.act('parcel')), // not offered now: 'not-allowed'
...(failed ? [button('Retry', () => failed.retry())] : []),
);
const lines = node.messages.filter((message) => !message.fromMe).map((message) => message.text);
list.textContent = lines.join(' · ');
});attempt does three things that every view needs:
- It awaits the call inside
try. A rejection therefore never ends up as an "Uncaught (in promise)" error in the console while the person sees nothing. - It turns results into messages with
if. - It turns error codes into messages in
catchwith a fallback for unknown codes.
The Retry button comes from the world itself because a failed message of the person has status: 'failed' and a retry() function. A button rendered from world.messages in subscribe appears and disappears on its own (Retry a failed message, Show whether a message was delivered).
The person's controls
In the webapp the person decides three things about your view and your code can only follow them:
- Whether to use it at all. The first time a person opens a world with your view, the webapp asks them to accept it. Your view loads only after they accept (Going live lists the content of the dialog).
- Whether to stay in it. The switch in the top bar of the webapp (in its menu on a phone) moves the person to the UNaIVERSE view of the same world and back at any time. Meanwhile your view keeps running hidden and is unchanged when they switch back.
- Which features of the browser it may use. Before your view uses the camera, the microphone, the location or another feature that the browser remembers for the whole site, it asks the person for permission with
askFor(The camera and the rest of the browser). A permission stays on that device for the address of your view. A refusal lasts only while your view is open.
A message that your view sends is a message of the person. Nothing marks it as coming from your view and nothing limits how often your view sends messages or requests actions. Since the person finds every such message under their name in the UNaIVERSE view, never send anything they did not ask for.
The 20 seconds
When the webapp starts your view, it waits 20 seconds for connectToHost() to succeed in your page. A page misses this limit in three cases: (1) your site is down or slow, (2) the page throws before it connects or (3) its address is localhost and nothing answers there on the computer of the person. The webapp then reacts in this way:
- the person sees the UNaIVERSE view in place of your view with a notice that the view of this world is not responding and a Try again button
- if your view connects later, the notice changes to "The view of this world is ready." with an Open it button (the webapp never switches the person without asking)
- Try again reloads your view at the last path it wrote with
setPath.
When the webapp does not accept the version of your kit ('unsupported'), the person gets the UNaIVERSE view with the same notice immediately.
Twenty seconds is a long time for a person and a short one for a phone on a bad network. Keep the startup light:
- Call
connectToHost()first as soon as your page runs and before it loads pictures, fonts, translations or anything from your own server. Load those in parallel with the connection or after it. - Keep the first download small. On a slow phone a huge bundle can use up the 20 seconds before your code runs.
- Never wait for the person before connecting (a "Start" button, a cookie banner). The webapp is waiting at the same time.
try/catch patterns
Every action awaited inside try. When an action called without await (onclick = () => world.send(text)) rejects, the console shows an "Uncaught (in promise)" error and the person learns nothing. Route every action through one function like attempt above.
React: the outcome in state. The example keeps in state the message for the person (setStatus(...)) and renders it from there. The world itself stays out of state because useWorld already returns the newest one.
Disable rather than refuse. canSend and now.actions tell you in advance what would fail. A disabled button with a reason next to it is better than an error after the click:
sendButton.disabled = !node.canSend;
sendButton.title = node.canSend ? '' : 'Not your turn';Show the codes you do not know. Because a later version of the kit can add codes, end every if/else chain with a fallback that shows the code (Something went wrong (${error.code})) and log the error with console.error(error).
Testing errors
A fake world reproduces only some of these cases:
'failed'and retry:failNext: truemakes the next message fail (the example uses it).'not-allowed': send an empty message, answer a question twice or callactwith a name that is not innow.actions.'refused'and the errors of the webapp such as a'failed'rejection never come from a fake world. Test your handling with a made-up error (showProblem({ code: 'failed' })).'no-host': open your page alone in a tab withoutfake.
Testing with fake worlds covers the other cases. The recipe Test failures with a fake world has a ready example.
Next steps
- Testing with fake worlds: everything a fake world can simulate.
- Debugging: how to find what went wrong and the common mistakes.
- Reference: Error codes,
send,act. - Component:
LoadingAndErrors.