Browse Source

Server.js: Error handler that works with ServerError

pull/750/head
Daniil Isakov 3 years ago
parent
commit
b1f3857e76
  1. 14
      src/lib/Server.js

14
src/lib/Server.js

@ -12,6 +12,7 @@ const serve = require('koa-static');
const debug = require('debug')('Server'); const debug = require('debug')('Server');
const ServerError = require('./ServerError');
const WireGuard = require('../services/WireGuard'); const WireGuard = require('../services/WireGuard');
const { const {
@ -27,6 +28,15 @@ module.exports = class Server {
this.app.keys = [crypto.randomBytes(256).toString('hex')]; this.app.keys = [crypto.randomBytes(256).toString('hex')];
this.app this.app
.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = { error: err.message };
ctx.app.emit('error', err, ctx);
}
})
.use(serve(path.join(__dirname, '..', 'www'))) .use(serve(path.join(__dirname, '..', 'www')))
.use(bodyParser()) .use(bodyParser())
.use(session(this.app)) .use(session(this.app))
@ -52,11 +62,11 @@ module.exports = class Server {
const { password } = ctx.request.body; const { password } = ctx.request.body;
if (typeof password !== 'string') { if (typeof password !== 'string') {
ctx.throw(401, JSON.stringify({ error: 'Missing: Password' })); throw new ServerError('Missing: Password', 401);
} }
if (password !== PASSWORD) { if (password !== PASSWORD) {
ctx.throw(401, JSON.stringify({ error: 'Incorrect Password' })); throw new ServerError('Incorrect Password', 401);
} }
ctx.session.authenticated = true; ctx.session.authenticated = true;

Loading…
Cancel
Save