1'use strict'; 2// Flags: --expose-internals 3 4const common = require('../common'); 5const tmpdir = require('../common/tmpdir'); 6 7// The following tests validate aggregate errors are thrown correctly 8// when both an operation and close throw. 9 10const path = require('path'); 11const { 12 readFile, 13 writeFile, 14 truncate, 15 lchmod, 16} = require('fs/promises'); 17const { 18 FileHandle, 19} = require('internal/fs/promises'); 20 21const assert = require('assert'); 22const originalFd = Object.getOwnPropertyDescriptor(FileHandle.prototype, 'fd'); 23 24let count = 0; 25async function createFile() { 26 const filePath = path.join(tmpdir.path, `aggregate_errors_${++count}.txt`); 27 await writeFile(filePath, 'content'); 28 return filePath; 29} 30 31async function checkAggregateError(op) { 32 try { 33 const filePath = await createFile(); 34 Object.defineProperty(FileHandle.prototype, 'fd', { 35 get: function() { 36 // Close is set by using a setter, 37 // so it needs to be set on the instance. 38 const originalClose = this.close; 39 this.close = async () => { 40 // close the file 41 await originalClose.call(this); 42 const closeError = new Error('CLOSE_ERROR'); 43 closeError.code = 456; 44 throw closeError; 45 }; 46 const opError = new Error('INTERNAL_ERROR'); 47 opError.code = 123; 48 throw opError; 49 } 50 }); 51 52 await assert.rejects(op(filePath), common.mustCall((err) => { 53 assert.strictEqual(err.name, 'AggregateError'); 54 assert.strictEqual(err.code, 123); 55 assert.strictEqual(err.errors.length, 2); 56 assert.strictEqual(err.errors[0].message, 'INTERNAL_ERROR'); 57 assert.strictEqual(err.errors[1].message, 'CLOSE_ERROR'); 58 return true; 59 })); 60 } finally { 61 Object.defineProperty(FileHandle.prototype, 'fd', originalFd); 62 } 63} 64(async function() { 65 tmpdir.refresh(); 66 await checkAggregateError((filePath) => truncate(filePath)); 67 await checkAggregateError((filePath) => readFile(filePath)); 68 await checkAggregateError((filePath) => writeFile(filePath, '123')); 69 if (common.isOSX) { 70 await checkAggregateError((filePath) => lchmod(filePath, 0o777)); 71 } 72})().then(common.mustCall()); 73