Skip to content

Commit 876fb09

Browse files
committed
fix(vue): route page lifecycle errors through Vue handlers
1 parent 6e16101 commit 876fb09

6 files changed

Lines changed: 237 additions & 4 deletions

File tree

‎packages/vue/src/hooks/lifecycle.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { printIonWarning } from "@ionic/core/components";
22
import type { ComponentInternalInstance } from "vue";
3-
import { getCurrentInstance } from "vue";
3+
import {
4+
callWithAsyncErrorHandling,
5+
ErrorCodes,
6+
getCurrentInstance,
7+
} from "vue";
48

59
import { LifecycleHooks } from "../utils";
610

@@ -29,7 +33,12 @@ const injectHook = (
2933
return;
3034
}
3135

32-
return args ? hook(...args) : hook();
36+
return callWithAsyncErrorHandling(
37+
hook,
38+
component,
39+
ErrorCodes.TRANSITION_HOOK,
40+
args
41+
);
3342
};
3443

3544
hooks.push(wrappedHook);

‎packages/vue/src/utils.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
LIFECYCLE_WILL_LEAVE,
77
} from "@ionic/core/components";
88
import type { Ref, ComponentPublicInstance } from "vue";
9+
import { callWithAsyncErrorHandling, ErrorCodes } from "vue";
910

1011
type LIFECYCLE_EVENTS =
1112
| typeof LIFECYCLE_WILL_ENTER
@@ -42,12 +43,20 @@ export const fireLifecycle = (
4243
lifecycle: LIFECYCLE_EVENTS
4344
) => {
4445
if (vueComponent?.[lifecycle]) {
45-
vueComponent[lifecycle].bind(vueInstance?.value)();
46+
callWithAsyncErrorHandling(
47+
vueComponent[lifecycle].bind(vueInstance?.value),
48+
vueInstance?.value?.$ ?? null,
49+
ErrorCodes.TRANSITION_HOOK
50+
);
4651
}
4752

4853
const instance = vueInstance?.value as any;
4954
if (instance?.[lifecycle]) {
50-
instance[lifecycle]();
55+
callWithAsyncErrorHandling(
56+
instance[lifecycle].bind(instance),
57+
vueInstance.value.$,
58+
ErrorCodes.TRANSITION_HOOK
59+
);
5160
}
5261

5362
/**

‎packages/vue/test/base/src/router/index.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@ const routes: Array<RouteRecordRaw> = [
2525
path: '/lifecycle-setup',
2626
component: () => import('@/views/LifecycleSetup.vue')
2727
},
28+
{
29+
path: '/lifecycle-errors',
30+
component: () => import('@/views/LifecycleErrorBoundary.vue'),
31+
children: [
32+
{
33+
path: '',
34+
component: () => import('@/views/LifecycleErrorPage.vue')
35+
}
36+
]
37+
},
2838
{
2939
path: '/overlays',
3040
component: () => import('@/views/Overlays.vue')
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<template>
2+
<ion-page>
3+
<ion-header>
4+
<ion-toolbar>
5+
<ion-title id="lifecycle-error">{{ message }}</ion-title>
6+
</ion-toolbar>
7+
</ion-header>
8+
<ion-content>
9+
<ion-router-outlet />
10+
</ion-content>
11+
</ion-page>
12+
</template>
13+
14+
<script setup lang="ts">
15+
import { IonContent, IonHeader, IonPage, IonRouterOutlet, IonTitle, IonToolbar } from '@ionic/vue';
16+
import { onErrorCaptured, ref } from 'vue';
17+
18+
const message = ref('No error captured');
19+
onErrorCaptured((error) => {
20+
message.value = error instanceof Error ? error.message : String(error);
21+
return false;
22+
});
23+
</script>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<template>
2+
<ion-page data-pageid="lifecycle-error">
3+
<p>The page transition should complete after the error is captured.</p>
4+
<ion-button router-link="/">Go home</ion-button>
5+
</ion-page>
6+
</template>
7+
8+
<script lang="ts">
9+
import { IonButton, IonPage, onIonViewWillEnter } from '@ionic/vue';
10+
import { defineComponent } from 'vue';
11+
import { useRoute } from 'vue-router';
12+
13+
export default defineComponent({
14+
components: { IonButton, IonPage },
15+
ionViewWillEnter() {
16+
if (this.route.query.api === 'options') {
17+
return this.fail();
18+
}
19+
},
20+
setup() {
21+
const route = useRoute();
22+
const fail = () => {
23+
const error = new Error('Ionic lifecycle error');
24+
if (route.query.async === 'true') {
25+
return Promise.reject(error);
26+
}
27+
throw error;
28+
};
29+
onIonViewWillEnter(() => {
30+
if (route.query.api !== 'options') {
31+
return fail();
32+
}
33+
});
34+
return { route, fail };
35+
},
36+
});
37+
</script>
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import { mount } from '@vue/test-utils';
2+
import { describe, expect, it } from 'vitest';
3+
import { createRouter, createWebHistory } from '@ionic/vue-router';
4+
import {
5+
IonicVue,
6+
IonPage,
7+
IonRouterOutlet,
8+
onIonViewDidEnter,
9+
onIonViewDidLeave,
10+
onIonViewWillEnter,
11+
onIonViewWillLeave,
12+
} from '@ionic/vue';
13+
import { defineComponent, h, onErrorCaptured, ref } from 'vue';
14+
import type { ComponentPublicInstance } from 'vue';
15+
import { waitForRouter } from './utils';
16+
import LifecycleErrorBoundary from '@/views/LifecycleErrorBoundary.vue';
17+
import LifecycleErrorPage from '@/views/LifecycleErrorPage.vue';
18+
19+
const lifecycles = [
20+
['ionViewWillEnter', onIonViewWillEnter],
21+
['ionViewDidEnter', onIonViewDidEnter],
22+
['ionViewWillLeave', onIonViewWillLeave],
23+
['ionViewDidLeave', onIonViewDidLeave],
24+
] as const;
25+
26+
describe.each(['composition', 'options', 'methods'] as const)('%s lifecycle errors', (api) => {
27+
describe.each(lifecycles)('%s', (lifecycle, registerHook) => {
28+
it.each([
29+
['synchronous', 'capture'],
30+
['asynchronous', 'capture'],
31+
['synchronous', 'app'],
32+
['asynchronous', 'app'],
33+
])('handles %s errors with the %s handler and completes navigation', async (timing, handler) => {
34+
const error = new Error(`${api} ${lifecycle} ${timing}`);
35+
const captured: unknown[] = [];
36+
const reported: unknown[] = [];
37+
const sources: (ComponentPublicInstance | null)[] = [];
38+
const messages = ref<string[]>([]);
39+
let receiver: ComponentPublicInstance | undefined;
40+
const fail = () => { throw error; };
41+
const hook = timing === 'asynchronous' ? async () => fail() : fail;
42+
const optionHook = function (this: ComponentPublicInstance) {
43+
receiver = this;
44+
return hook();
45+
};
46+
const Page = defineComponent({
47+
name: 'LifecycleErrorPage',
48+
...(api === 'options' ? { [lifecycle]: optionHook } : {}),
49+
...(api === 'methods' ? { methods: { [lifecycle]: optionHook } } : {}),
50+
setup() {
51+
if (api === 'composition') {
52+
registerHook(hook);
53+
}
54+
return { marker: 'error-page' };
55+
},
56+
render: () => h(IonPage, { 'data-pageid': 'error' }, () => 'Error page'),
57+
});
58+
const OtherPage = defineComponent({
59+
render: () => h(IonPage, { 'data-pageid': 'other' }, () => 'Other page'),
60+
});
61+
const Boundary = defineComponent({
62+
setup() {
63+
onErrorCaptured((err, instance) => {
64+
captured.push(err);
65+
sources.push(instance);
66+
if (handler === 'capture') {
67+
messages.value.push((err as Error).message);
68+
return false;
69+
}
70+
});
71+
return () => [h('p', { id: 'errors' }, messages.value.join(', ')), h(IonRouterOutlet)];
72+
},
73+
});
74+
const router = createRouter({
75+
history: createWebHistory(),
76+
routes: [
77+
{ path: '/', component: OtherPage },
78+
{ path: '/error', component: Page },
79+
{ path: '/other', component: OtherPage },
80+
],
81+
});
82+
await router.push('/');
83+
await router.isReady();
84+
const wrapper = mount(Boundary, {
85+
global: {
86+
plugins: [router, [IonicVue, { animated: false }]],
87+
config: {
88+
errorHandler(err) {
89+
reported.push(err);
90+
messages.value.push((err as Error).message);
91+
},
92+
},
93+
},
94+
});
95+
try {
96+
await router.push('/error');
97+
await waitForRouter();
98+
const page = wrapper.findComponent(Page);
99+
expect(page.classes()).not.toContain('ion-page-invisible');
100+
await router.push('/other');
101+
await waitForRouter();
102+
expect(wrapper.find('[data-pageid="other"]').classes()).not.toContain('ion-page-invisible');
103+
expect(captured).toEqual([error]);
104+
expect(reported).toEqual(handler === 'app' ? [error] : []);
105+
expect(sources).toEqual([page.vm.$.proxy]);
106+
expect(wrapper.find('#errors').text()).toBe(error.message);
107+
if (api !== 'composition') {
108+
expect(receiver).toBe(page.vm.$.proxy);
109+
}
110+
} finally {
111+
wrapper.unmount();
112+
}
113+
});
114+
});
115+
});
116+
117+
describe('Lifecycle error reproduction', () => {
118+
it.each([
119+
['composition', 'false'],
120+
['composition', 'true'],
121+
['options', 'false'],
122+
['options', 'true'],
123+
])('captures %s errors with async=%s', async (api, asynchronous) => {
124+
const router = createRouter({
125+
history: createWebHistory(),
126+
routes: [{
127+
path: '/lifecycle-errors',
128+
component: LifecycleErrorBoundary,
129+
children: [{ path: '', component: LifecycleErrorPage }],
130+
}],
131+
});
132+
await router.push(`/lifecycle-errors?api=${api}&async=${asynchronous}`);
133+
await router.isReady();
134+
const wrapper = mount(IonRouterOutlet, {
135+
global: { plugins: [router, [IonicVue, { animated: false }]] },
136+
});
137+
try {
138+
await waitForRouter();
139+
expect(wrapper.find('#lifecycle-error').text()).toBe('Ionic lifecycle error');
140+
expect(wrapper.find('[data-pageid="lifecycle-error"]').classes()).not.toContain('ion-page-invisible');
141+
} finally {
142+
wrapper.unmount();
143+
}
144+
});
145+
});

0 commit comments

Comments
 (0)