Skip to content

Commit 42fa2a8

Browse files
committed
adds error handling middleware for 404 & 50x
- includes basic static files for each Former-commit-id: abac437c0b26b74db798a73648c8e9f0d1cd1dd3 [formerly 79d7707] Former-commit-id: 37fa3f5
1 parent 8470b10 commit 42fa2a8

File tree

4 files changed

+25
-11
lines changed

4 files changed

+25
-11
lines changed

public/404.html

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
404 Not Found

public/50x.html

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Error, Try Again!

server/App.ls

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ module.exports =
3232
app
3333
..on \error (err) ->
3434
console.error(pe.render err) # error handler
35+
..use middleware.error-handler # 404 & 50x handler
3536
..use middleware.app-cache # offline support
3637
..use(koa-static './public') # static assets handler
3738
..use middleware.config-locals # load config into locals

server/middleware.ls

+22-11
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,25 @@ require! {
99

1010
global <<< require \prelude-ls
1111

12-
config = JSON.parse(fs.read-file-sync './config.json') # intentionally crashes if malformed & sync
13-
14-
export four-oh-four-handler = (next) ->*
15-
return unless @status is 404 # guard
16-
@status = 404 # so koa doesn't 200 or 404
17-
switch (@accepts \html \json)
18-
| \json =>
19-
@body = message: 'Page Not Found!'
20-
| otherwise => # TODO load static jade assets
21-
@type = \html
22-
@body = '404, Page Not Found!'
12+
cwd = process.cwd!
13+
config = require "#cwd/config.json"
14+
html404 = fs.read-file-sync "#cwd/public/404.html" .to-string!
15+
html50x = fs.read-file-sync "#cwd/public/50x.html" .to-string!
16+
17+
18+
export error-handler = (next) ->*
19+
try
20+
yield next
21+
if @status is 404 then throw 404
22+
catch
23+
@status = if typeof! e is \Number then e else e.status or 500 # default 500
24+
switch @accepts(\html \text \json) # -> out!
25+
| \json =>
26+
@body = message: if @status is 404 then 'Page Not Found!' else 'Error, Try Again!'
27+
| otherwise =>
28+
@type = \html
29+
@body = if @status is 404 then html404 else html50x
30+
@app.emit \error, e, @ # report to koa, too
2331

2432
# app-cache manifest needs headers
2533
export app-cache = (next) ->*
@@ -32,6 +40,7 @@ export app-cache = (next) ->*
3240
@status = 404
3341
yield next
3442

43+
3544
# localize config.json for env
3645
export config-locals = (next) ->*
3746
config <<< config[@locals.env] # merge in current env's config
@@ -45,6 +54,8 @@ export config-locals = (next) ->*
4554
"#v:#{@locals.port}"
4655
yield next
4756

57+
58+
# react
4859
export react = (next) ->* # set body to react tree
4960
locals = {} <<< @locals
5061
path = url.parse (@url or '/') .pathname

0 commit comments

Comments
 (0)