combine.fm/lib/error-handler.js

41 lines
925 B
JavaScript
Raw Normal View History

2016-10-23 23:04:32 +01:00
import debuglog from 'debug';
2017-10-23 17:58:23 +01:00
const debug = debuglog('combine.fm');
2016-10-23 23:04:32 +01:00
2017-05-26 19:47:17 +01:00
export default function (raven) {
2018-04-13 21:44:31 +01:00
return async function error(ctx, next) {
ctx.set('Server', 'Nintendo 64');
2016-10-23 23:04:32 +01:00
try {
2018-04-13 21:44:31 +01:00
await next();
2016-10-23 23:04:32 +01:00
} catch (err) {
if (err.status === 404) {
2018-04-13 21:44:31 +01:00
ctx.body = '404 Page Not Found';
2016-10-23 23:04:32 +01:00
} else if (err.status >= 400 && err.status < 500) {
2018-04-13 21:44:31 +01:00
ctx.status = err.status;
ctx.body = err.error;
2016-10-23 23:04:32 +01:00
} else {
debug('Error: %o', err);
2017-05-26 19:47:17 +01:00
raven.captureException(err);
2016-10-23 23:04:32 +01:00
throw err;
}
}
2018-04-13 21:44:31 +01:00
if (ctx.status !== 404) return;
2016-10-23 23:04:32 +01:00
2018-04-13 21:44:31 +01:00
switch (ctx.accepts('html', 'json')) {
2016-10-23 23:04:32 +01:00
case 'html':
2018-04-13 21:44:31 +01:00
ctx.type = 'html';
ctx.body = '404 Page Not Found';
2016-10-23 23:04:32 +01:00
break;
case 'json':
2018-04-13 21:44:31 +01:00
ctx.body = {
2016-10-23 23:04:32 +01:00
message: 'Page Not Found',
};
break;
default:
2018-04-13 21:44:31 +01:00
ctx.type = 'text';
ctx.body = 'Page Not Found';
2016-10-23 23:04:32 +01:00
}
};
}