From b1f3857e7682adc83829f9287cf91dfd033074dc Mon Sep 17 00:00:00 2001 From: Daniil Isakov <12859907+oplexz@users.noreply.github.com> Date: Thu, 11 Jan 2024 21:21:16 +0300 Subject: [PATCH] Server.js: Error handler that works with ServerError --- src/lib/Server.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/lib/Server.js b/src/lib/Server.js index b9538c05..39198532 100644 --- a/src/lib/Server.js +++ b/src/lib/Server.js @@ -12,6 +12,7 @@ const serve = require('koa-static'); const debug = require('debug')('Server'); +const ServerError = require('./ServerError'); const WireGuard = require('../services/WireGuard'); const { @@ -27,6 +28,15 @@ module.exports = class Server { this.app.keys = [crypto.randomBytes(256).toString('hex')]; 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(bodyParser()) .use(session(this.app)) @@ -52,11 +62,11 @@ module.exports = class Server { const { password } = ctx.request.body; if (typeof password !== 'string') { - ctx.throw(401, JSON.stringify({ error: 'Missing: Password' })); + throw new ServerError('Missing: Password', 401); } if (password !== PASSWORD) { - ctx.throw(401, JSON.stringify({ error: 'Incorrect Password' })); + throw new ServerError('Incorrect Password', 401); } ctx.session.authenticated = true;