Catch a child's error
When a child component throws, the error travels up the tree. If nothing catches
it, Vue logs it and the whole app can break. onErrorCaptured gives a parent a
chance to handle it.
Call it in setup with a handler. Vue calls that handler whenever a descendant
throws:
import { onErrorCaptured, ref } from 'vue';
const message = ref('');
onErrorCaptured((error) => {
message.value = error.message;
return false;
});
The handler receives the error, the instance that threw, and some info. Return
false to stop the error from travelling further up the tree. Returning
anything else lets it continue.
The parent can then render something useful from message instead of leaving a
blank space.
The file already defines a Broken child that throws, and an onErrorCaptured
handler that swallows the error. Record the message and render it. The Test
mounts your component, waits for the error to be handled, and checks the message
is on screen. The starter shows nothing, so the Test fails.
Challenge
The child throws and the parent shows nothing. Record the error: export an App
component from App.vue whose onErrorCaptured handler stores
error.message and renders it.
The Test mounts your component and expects the child's message on screen. The starter captures the error but renders no message, so the Test fails.