implement this.error

This commit is contained in:
Rich Harris
2018-02-18 09:48:32 -05:00
parent d55401d45b
commit cb12231053
7 changed files with 168 additions and 61 deletions

View File

@@ -94,9 +94,7 @@ export default function middleware({ routes }: {
} }
}, },
get_route_handler(client_info.assetsByChunkName, routes, template), get_route_handler(client_info.assetsByChunkName, routes, template)
get_not_found_handler(client_info.assetsByChunkName, routes, template)
].filter(Boolean)); ].filter(Boolean));
return middleware; return middleware;
@@ -120,7 +118,7 @@ function get_asset_handler({ pathname, type, cache, body }: {
const resolved = Promise.resolve(); const resolved = Promise.resolve();
function get_route_handler(chunks: Record<string, string>, routes: RouteObject[], template: Template) { function get_route_handler(chunks: Record<string, string>, routes: RouteObject[], template: Template) {
function handle_route(route: RouteObject, req: Req, res: ServerResponse, next: () => void) { function handle_route(route: RouteObject, req: Req, res: ServerResponse) {
req.params = route.params(route.pattern.exec(req.pathname)); req.params = route.params(route.pattern.exec(req.pathname));
const mod = route.module; const mod = route.module;
@@ -135,15 +133,20 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
const data = { params: req.params, query: req.query }; const data = { params: req.params, query: req.query };
let redirect: { statusCode: number, location: string }; let redirect: { statusCode: number, location: string };
let error; let error: { statusCode: number, message: Error | string };
Promise.resolve( Promise.resolve(
mod.preload ? mod.preload.call({ mod.preload ? mod.preload.call({
redirect: (statusCode: number, location: string) => { redirect: (statusCode: number, location: string) => {
redirect = { statusCode, location }; redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
error = { statusCode, message };
} }
}, req) : {} }, req) : {}
).then(preloaded => { ).catch(err => {
error = { statusCode: 500, message: err };
}).then(preloaded => {
if (redirect) { if (redirect) {
res.statusCode = redirect.statusCode; res.statusCode = redirect.statusCode;
res.setHeader('Location', redirect.location); res.setHeader('Location', redirect.location);
@@ -152,6 +155,11 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
return; return;
} }
if (error) {
handle_error(req, res, error.statusCode, error.message);
return;
}
const serialized = try_serialize(preloaded); // TODO bail on non-POJOs const serialized = try_serialize(preloaded); // TODO bail on non-POJOs
Object.assign(data, preloaded); Object.assign(data, preloaded);
@@ -220,60 +228,28 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
}; };
} }
handler(req, res, next); handler(req, res, () => {
handle_not_found(req, res, 404, 'Not found');
});
} else { } else {
// no matching handler for method — 404 // no matching handler for method — 404
next(); handle_not_found(req, res, 404, 'Not found');
} }
} }
} }
const error_route = routes.find((route: RouteObject) => route.error === '5xx') const not_found_route = routes.find((route: RouteObject) => route.error === '4xx');
return function find_route(req: Req, res: ServerResponse, next: () => void) { function handle_not_found(req: Req, res: ServerResponse, statusCode: number, message: Error | string) {
const url = req.pathname; res.statusCode = statusCode;
try {
for (const route of routes) {
if (!route.error && route.pattern.test(url)) return handle_route(route, req, res, next);
}
// no matching route — 404
next();
} catch (error) {
console.error(error);
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
const rendered = error_route ? error_route.module.render({
status: 500,
error
}) : { head: '', css: null, html: 'Not found' };
const { head, css, html } = rendered;
res.end(template.render({
scripts: `<script src='/client/${chunks.main}'></script>`,
html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
styles: (css && css.code ? `<style>${css.code}</style>` : '')
}));
}
};
}
function get_not_found_handler(chunks: Record<string, string>, routes: RouteObject[], template: Template) {
const route = routes.find((route: RouteObject) => route.error === '4xx');
return function handle_not_found(req: Req, res: ServerResponse) {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
const rendered = route ? route.module.render({ const error = message instanceof Error ? message : new Error(message);
const rendered = not_found_route ? not_found_route.module.render({
status: 404, status: 404,
message: 'Not found' error
}) : { head: '', css: null, html: 'Not found' }; }) : { head: '', css: null, html: error.message };
const { head, css, html } = rendered; const { head, css, html } = rendered;
@@ -283,6 +259,47 @@ function get_not_found_handler(chunks: Record<string, string>, routes: RouteObje
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`, head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
styles: (css && css.code ? `<style>${css.code}</style>` : '') styles: (css && css.code ? `<style>${css.code}</style>` : '')
})); }));
}
const error_route = routes.find((route: RouteObject) => route.error === '5xx');
function handle_error(req: Req, res: ServerResponse, statusCode: number, message: Error | string) {
if (statusCode >= 400 && statusCode < 500) {
return handle_not_found(req, res, statusCode, message);
}
res.statusCode = statusCode;
res.setHeader('Content-Type', 'text/html');
const error = message instanceof Error ? message : new Error(message);
const rendered = error_route ? error_route.module.render({
status: 500,
error
}) : { head: '', css: null, html: `Internal server error: ${error.message}` };
const { head, css, html } = rendered;
res.end(template.render({
scripts: `<script src='/client/${chunks.main}'></script>`,
html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
styles: (css && css.code ? `<style>${css.code}</style>` : '')
}));
}
return function find_route(req: Req, res: ServerResponse, next: () => void) {
const url = req.pathname;
try {
for (const route of routes) {
if (!route.error && route.pattern.test(url)) return handle_route(route, req, res);
}
handle_not_found(req, res, 404, 'Not found');
} catch (error) {
handle_error(req, res, 500, error);
}
}; };
} }

View File

@@ -75,20 +75,38 @@ function render(Component: ComponentConstructor, data: any, scroll: ScrollPositi
function prepare_route(Component: ComponentConstructor, data: RouteData) { function prepare_route(Component: ComponentConstructor, data: RouteData) {
let redirect: { statusCode: number, location: string } = null; let redirect: { statusCode: number, location: string } = null;
let error: { statusCode: number, message: Error | string } = null;
if (!Component.preload) { if (!Component.preload) {
return { Component, data, redirect }; return { Component, data, redirect, error };
} }
if (!component && window.__SAPPER__ && window.__SAPPER__.preloaded) { if (!component && window.__SAPPER__ && window.__SAPPER__.preloaded) {
return { Component, data: Object.assign(data, window.__SAPPER__.preloaded), redirect }; return { Component, data: Object.assign(data, window.__SAPPER__.preloaded), redirect, error };
} }
return Promise.resolve(Component.preload.call({ return Promise.resolve(Component.preload.call({
redirect: (statusCode: number, location: string) => { redirect: (statusCode: number, location: string) => {
redirect = { statusCode, location }; redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
error = { statusCode, message };
} }
}, data)).then(preloaded => { }, data)).catch(err => {
error = { statusCode: 500, message: err };
}).then(preloaded => {
if (error) {
const route = error.statusCode >= 400 && error.statusCode < 500
? errors['4xx']
: errors['5xx'];
return route.load().then(({ default: Component }: { default: ComponentConstructor }) => {
const err = error.message instanceof Error ? error.message : new Error(error.message);
Object.assign(data, { status: error.statusCode, error: err });
return { Component, data, redirect: null };
});
}
Object.assign(data, preloaded) Object.assign(data, preloaded)
return { Component, data, redirect }; return { Component, data, redirect };
}); });
@@ -117,7 +135,10 @@ function navigate(target: Target, id: number) {
const token = current_token = {}; const token = current_token = {};
return loaded.then(({ Component, data, redirect }) => { return loaded.then(({ Component, data, redirect }) => {
if (redirect) return goto(redirect.location, { replaceState: true }); if (redirect) {
return goto(redirect.location, { replaceState: true });
}
render(Component, data, scroll_history[id], token); render(Component, data, scroll_history[id], token);
}); });
} }

View File

@@ -3,8 +3,8 @@
</:Head> </:Head>
<Layout page='home'> <Layout page='home'>
<h1>{{status}}</h1> <h1>Not found</h1>
<p>{{message}}</p> <p>{{error.message}}</p>
</Layout> </Layout>
<script> <script>

View File

@@ -1,9 +1,9 @@
<:Head> <:Head>
<title>{{status}}</title> <title>Internal server error</title>
</:Head> </:Head>
<Layout page='home'> <Layout page='home'>
<h1>{{status}}</h1> <h1>Internal server error</h1>
<p>{{error.message}}</p> <p>{{error.message}}</p>
</Layout> </Layout>

View File

@@ -4,6 +4,8 @@
<li><a href='/about'>about</a></li> <li><a href='/about'>about</a></li>
<li><a href='/slow-preload'>slow preload</a></li> <li><a href='/slow-preload'>slow preload</a></li>
<li><a href='/redirect-from'>redirect</a></li> <li><a href='/redirect-from'>redirect</a></li>
<li><a href='/blog/nope'>broken link</a></li>
<li><a href='/blog/throw-an-error'>error link</a></li>
<li><a rel=prefetch class='{{page === "blog" ? "selected" : ""}}' href='/blog'>blog</a></li> <li><a rel=prefetch class='{{page === "blog" ? "selected" : ""}}' href='/blog'>blog</a></li>
</ul> </ul>
</nav> </nav>

View File

@@ -59,8 +59,21 @@
// is called [slug].html // is called [slug].html
const { slug } = params; const { slug } = params;
return fetch(`/api/blog/${slug}`).then(r => r.json()).then(post => { if (slug === 'throw-an-error') {
return { post }; return this.error(500, 'something went wrong');
}
return fetch(`/api/blog/${slug}`).then(r => {
if (r.status === 200) {
return r.json().then(post => ({ post }));
this.error(r.status, '')
}
if (r.status === 404) {
this.error(404, 'Not found');
} else {
throw new Error('Something went wrong');
}
}); });
} }
}; };

View File

@@ -308,7 +308,7 @@ function run(env) {
}); });
}); });
it('redirects on client', () => { it('redirects in client', () => {
return nightmare.goto(base) return nightmare.goto(base)
.wait('[href="/redirect-from"]') .wait('[href="/redirect-from"]')
.click('[href="/redirect-from"]') .click('[href="/redirect-from"]')
@@ -322,6 +322,60 @@ function run(env) {
assert.equal(title, 'redirected'); assert.equal(title, 'redirected');
}); });
}); });
it('handles 4xx error on server', () => {
return nightmare.goto(`${base}/blog/nope`)
.path()
.then(path => {
assert.equal(path, '/blog/nope');
})
.then(() => nightmare.page.title())
.then(title => {
assert.equal(title, 'Not found')
});
});
it('handles 4xx error in client', () => {
return nightmare.goto(base)
.init()
.click('[href="/blog/nope"]')
.wait(200)
.path()
.then(path => {
assert.equal(path, '/blog/nope');
})
.then(() => nightmare.page.title())
.then(title => {
assert.equal(title, 'Not found');
});
});
it('handles non-4xx error on server', () => {
return nightmare.goto(`${base}/blog/throw-an-error`)
.path()
.then(path => {
assert.equal(path, '/blog/throw-an-error');
})
.then(() => nightmare.page.title())
.then(title => {
assert.equal(title, 'Internal server error')
});
});
it('handles non-4xx error in client', () => {
return nightmare.goto(base)
.init()
.click('[href="/blog/throw-an-error"]')
.wait(200)
.path()
.then(path => {
assert.equal(path, '/blog/throw-an-error');
})
.then(() => nightmare.page.title())
.then(title => {
assert.equal(title, 'Internal server error');
});
});
}); });
describe('headers', () => { describe('headers', () => {