The fail
method of the assert
module in Node.js throws an AssertionError with an error message.
The process is illustrated below:
To use the fail
method, you will need to install the assert
module using the command prompt, as shown below:
npm install assert
After the installation is complete, you will need to import the assert
module into the program, as shown below:
const assert = require('assert');
The prototype of the fail
method is shown below:
fail([message])
The fail
method takes a single optional parameter that may either be an error message or an instance of an Error object.
The fail
method throws an AssertionError
with the provided message
parameter. If the message
parameter is not provided, a default error message is assigned.
Similarly, if the message
parameter is an instance of an Error
object, then the Error
instance is thrown instead of the AssertionError
.
The code below shows how the fail
method works in Node.js:
const assert = require('assert');// default error messagetry{assert.fail()}catch(error){console.log(error.message)}// provided error messagetry{assert.fail('This error message should be displayed')}catch(error){console.log(error.message)}// provided Error objecttry{assert.fail(new TypeError('My custom error object'))}catch(error){console.log(error.message)}
The code above uses three different expressions to show the behavior of the fail
method.
In the first call to the fail
method in line , no message
parameter is provided. The fail
method proceeds to throw an error, which triggers the catch
branch of the try-catch
block. The code outputs the message associated with the error, i.e., the default message associated with the fail
method.
In the call to the fail
method in line , the message
parameter is provided. The fail
method proceeds to throw an error, which triggers the catch
branch of the try-catch
block. The code outputs the message associated with the error, i.e., the provided message
parameter.
In the call to the fail
method in line , the message
parameter is an instance of an Error
object. The fail
method proceeds to throw an error, which triggers the catch
branch of the try-catch
block. The code outputs the message associated with the Error
instance, i.e., the initialized string.