Skip to content

Commit

Permalink
doc: update assert.throws() examples
Browse files Browse the repository at this point in the history
This updates two outdated examples to the current implementation.

PR-URL: #28263
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
BridgeAR committed Oct 1, 2019
1 parent 48d1ea5 commit 8fd7184
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions doc/api/assert.md
Original file line number Diff line number Diff line change
Expand Up @@ -1188,10 +1188,15 @@ assert.throws(
assert.throws(
() => {
const otherErr = new Error('Not found');
otherErr.code = 404;
// Copy all enumerable properties from `err` to `otherErr`.
for (const [key, value] of Object.entries(err)) {
otherErr[key] = value;
}
throw otherErr;
},
err // This tests for `message`, `name` and `code`.
// The error's `message` and `name` properties will also be checked when using
// an error as validation object.
err
);
```

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

// If the error message does not match, the error from within the function is
// not caught.
// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// Error: First
// at throwingFirst (repl:2:9)
// AssertionError [ERR_ASSERTION]
```

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

0 comments on commit 8fd7184

Please sign in to comment.