Skip to content

Commit 8fd7184

Browse files
committed
doc: update assert.throws() examples
This updates two outdated examples to the current implementation. PR-URL: #28263 Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 48d1ea5 commit 8fd7184

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

doc/api/assert.md

+13-9
Original file line numberDiff line numberDiff line change
@@ -1188,10 +1188,15 @@ assert.throws(
11881188
assert.throws(
11891189
() => {
11901190
const otherErr = new Error('Not found');
1191-
otherErr.code = 404;
1191+
// Copy all enumerable properties from `err` to `otherErr`.
1192+
for (const [key, value] of Object.entries(err)) {
1193+
otherErr[key] = value;
1194+
}
11921195
throw otherErr;
11931196
},
1194-
err // This tests for `message`, `name` and `code`.
1197+
// The error's `message` and `name` properties will also be checked when using
1198+
// an error as validation object.
1199+
err
11951200
);
11961201
```
11971202

@@ -1234,9 +1239,10 @@ assert.throws(
12341239
assert(err instanceof Error);
12351240
assert(/value/.test(err));
12361241
// Returning anything from validation functions besides `true` is not
1237-
// recommended. Doing so results in the caught error being thrown again.
1238-
// That is usually not the desired outcome. Throw an error about the
1239-
// specific validation that failed instead (as done in this example).
1242+
// recommended. By doing that, it's not clear what part of the validation
1243+
// failed. Instead, throw an error about the specific validation that failed
1244+
// (as done in this example) and add as much helpful debugging information
1245+
// to that error as possible.
12401246
return true;
12411247
},
12421248
'unexpected error'
@@ -1278,11 +1284,9 @@ assert.throws(notThrowing, 'Second');
12781284
// It does not throw because the error messages match.
12791285
assert.throws(throwingSecond, /Second$/);
12801286

1281-
// If the error message does not match, the error from within the function is
1282-
// not caught.
1287+
// If the error message does not match, an AssertionError is thrown.
12831288
assert.throws(throwingFirst, /Second$/);
1284-
// Error: First
1285-
// at throwingFirst (repl:2:9)
1289+
// AssertionError [ERR_ASSERTION]
12861290
```
12871291

12881292
Due to the confusing notation, it is recommended not to use a string as the

0 commit comments

Comments
 (0)