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

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

View File

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

View File

@@ -4,6 +4,8 @@
<li><a href='/about'>about</a></li>
<li><a href='/slow-preload'>slow preload</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>
</ul>
</nav>

View File

@@ -59,8 +59,21 @@
// is called [slug].html
const { slug } = params;
return fetch(`/api/blog/${slug}`).then(r => r.json()).then(post => {
return { post };
if (slug === 'throw-an-error') {
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)
.wait('[href="/redirect-from"]')
.click('[href="/redirect-from"]')
@@ -322,6 +322,60 @@ function run(env) {
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', () => {