Bird
0
0

Which of the following Node.js code snippets correctly logs unhandled promise rejections and then exits the process with a failure code?

hard📝 Application Q8 of 15
Node.js - Error Handling Patterns
Which of the following Node.js code snippets correctly logs unhandled promise rejections and then exits the process with a failure code?
Aprocess.on('rejectionHandled', (reason) => { console.error('Unhandled rejection:', reason); process.exit(1); });
Bprocess.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); }); process.exit(1);
Cprocess.on('unhandledRejection', (reason) => { console.log('Handled:', reason); process.exit(0); });
Dprocess.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); process.exit(1); });
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct event and handler

    The event for unhandled promise rejections is 'unhandledRejection'.
  2. Step 2: Log the rejection reason

    Use console.error to log the rejection reason.
  3. Step 3: Exit process after logging

    Call process.exit(1) inside the handler to exit with failure code after logging.
  4. Final Answer:

    process.on('unhandledRejection', (reason) => { console.error('Unhandled rejection:', reason); process.exit(1); }); correctly implements all steps.
  5. Quick Check:

    Logs and exits inside handler [OK]
Quick Trick: Exit process inside unhandledRejection handler [OK]
Common Mistakes:
  • Calling process.exit outside the handler causing immediate exit
  • Using wrong event like 'rejectionHandled'
  • Exiting with code 0 which indicates success

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes