Added try catch for errors in all domain event listeners (#15976)

refs https://github.com/TryGhost/Team/issues/2370

Reduces the amount of unhandled errors that could cause a crash in Ghost
This commit is contained in:
Simon Backx 2022-12-13 11:28:02 +01:00 committed by GitHub
parent 9579791185
commit 520b19e313
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 3 deletions

View File

@ -1,4 +1,5 @@
const EventEmitter = require('events').EventEmitter;
const logging = require('@tryghost/logging');
/**
* @template T
@ -23,12 +24,19 @@ class DomainEvents {
* @template Data
* @template {IEvent<Data>} EventClass
* @param {ConstructorOf<EventClass>} Event
* @param {(event: EventClass) => void} handler
* @param {(event: EventClass) => Promise<void> | void} handler
*
* @returns {void}
*/
static subscribe(Event, handler) {
DomainEvents.ee.on(Event.name, handler);
DomainEvents.ee.on(Event.name, async (event) => {
try {
await handler(event);
} catch (e) {
logging.error('Unhandled error in event handler for event: ' + Event.name);
logging.error(e);
}
});
}
/**

View File

@ -19,6 +19,7 @@
"devDependencies": {
"c8": "7.12.0",
"mocha": "10.2.0",
"should": "13.2.3"
"should": "13.2.3",
"@tryghost/logging": "2.3.2"
}
}