본문으로 바로가기
COMMUNITY모든 이야기

Node.js EventEmitter에서 async 리스너 사용 시 에러 핸들링 불가 문제

빗방울 2026.10.31 05:44 2분 읽기 조회 135 · 추천 1

특정 이벤트 발생 시 비동기 로직을 처리하고, 해당 로직에서 발생하는 예외를 메인 프로세스에서 캐치하려고 합니다.

코드:

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('data', async (data) => {
  if (data === 'fail') {
    throw new Error('Async Error Occurred');
  }
  console.log('Success');
});

try {
  emitter.emit('data', 'fail');
} catch (e) {
  console.error('Caught:', e.message);
}

시도: 1. `emit` 호출부를 `try-catch` 블록으로 감싸 처리함.

2. `emitter.on` 내부의 콜백 함수를 `async`로 선언함.

질문: `EventEmitter.emit`은 리턴값으로 리스너들의 실행 결과(Promise)를 반환하지 않는데, 비동기 리스너에서 발생한 에러를 외부에서 어떻게 포착할 수 있습니까?

모든 이야기1511

가벼운 안부부터 깊은 생각까지, 함께 나눠요.

글쓰기
총 1511개의 이야기
댓글