npm.nicfv.com

    Custom Exception Message

    In some cases, we may want to override the default exception message. This can easily be done by adding an additional string argument at the end of any test. This can help determine which test failed from a script of several tests. Even if a message is overwritten, it will still say which test number failed.

    In this example scenario, we want to check the price of an item and continue processing if it is below a certain threshold. Since we are catching these exceptions, the script will continue to run anyway, but will immediately exit the try block and advance straight into the catch block. Notice how the output does not contain the string "Processing item."

    Follow these steps to create a new project workspace and install the t6 dependency to run this example.

    # Create and open project folder
    mkdir Custom_Message_demo
    cd Custom_Message_demo
    # Initialize project and install dependencies
    npm init -y
    npm i t6@1.1.9
    # Create and open source file
    touch "Custom Message.mjs"
    open "Custom Message.mjs"

    Copy and paste this source code into Custom Message.mjs.

    import { T6 } from 't6';

    // Here's a simulation of
    // an API to obtain the
    // list price of an item.
    function getPrice() {
    return 50;
    }

    // Let's say our cap is $40 to
    // continue processing. We can
    // assert that the price is less
    // than or equal to $40 or throw
    // an error. For this example,
    // we will catch the exception.
    try {
    T6.le(getPrice(), 40);
    console.log('Processing item.');
    } catch (e) {
    console.log(e.message);
    }

    // Here is the same logic using
    // a custom exception message.
    try {
    T6.le(getPrice(), 40, 'Price exceeded $40 limit.');
    console.log('Processing item.');
    } catch (e) {
    console.log(e.message);
    }

    In Custom_Message_demo/, execute Custom Message.mjs with NodeJS to generate an output.

    node "Custom Message.mjs"
    

    You should expect to see an output similar to the one below.

    Exception found in test #1! The test value of 50 was not less than nor equal to the expected value of 40.
    Exception found in test #2! Price exceeded $40 limit.
    
    MMNEPVFCICPMFPCPTTAAATR