From 8fd7184959449669fcf04a40c8dd2b887e53ed13 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 17 Jun 2019 16:35:10 +0200 Subject: doc: update assert.throws() examples This updates two outdated examples to the current implementation. PR-URL: https://github.com/nodejs/node/pull/28263 Reviewed-By: Rich Trott Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell --- doc/api/assert.md | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'doc') diff --git a/doc/api/assert.md b/doc/api/assert.md index 06eb57bad4..86a3d1c0e7 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -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 ); ``` @@ -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' @@ -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 -- cgit v1.2.3