diff --git a/app.js b/app.js index 461218e..ca4e7aa 100644 --- a/app.js +++ b/app.js @@ -15,6 +15,7 @@ import recent from './routes/recent'; import search from './routes/search'; import share from './routes/share'; import itunesProxy from './routes/itunes-proxy'; +import errorHandler from './lib/error-handler'; const debug = debuglog('match.audio'); @@ -22,6 +23,8 @@ process.env.VUE_ENV = 'server'; const app = koa(); +app.use(errorHandler()); + app.use(bodyparser()); app.use(cors()); app.use(compress({ flush: zlib.Z_SYNC_FLUSH })); diff --git a/lib/error-handler.js b/lib/error-handler.js new file mode 100644 index 0000000..d6c8020 --- /dev/null +++ b/lib/error-handler.js @@ -0,0 +1,39 @@ +import debuglog from 'debug'; + +const debug = debuglog('match.audio'); + +export default function () { + return function* error(next) { + this.set('Server', 'Nintendo 64'); + try { + yield next; + } catch (err) { + if (err.status === 404) { + this.body = '404 Page Not Found'; + } else if (err.status >= 400 && err.status < 500) { + this.status = err.status; + this.body = err.error; + } else { + debug('Error: %o', err); + throw err; + } + } + + if (this.status !== 404) return; + + switch (this.accepts('html', 'json')) { + case 'html': + this.type = 'html'; + this.body = '404 Page Not Found'; + break; + case 'json': + this.body = { + message: 'Page Not Found', + }; + break; + default: + this.type = 'text'; + this.body = 'Page Not Found'; + } + }; +} diff --git a/public/src/components/search.vue b/public/src/components/search.vue index 82ced27..3bcded1 100644 --- a/public/src/components/search.vue +++ b/public/src/components/search.vue @@ -1,12 +1,18 @@