DEV Community

Discussion on: Tribonacci

Collapse
 
aminnairi profile image
Amin • Edited

Hi there, great article. Thanks for sharing your solution for the tribonacci.

Personally I like to go further in the error handling by creating my own error classes just like custom exception classes in PHP.

"use strict";

class LogInvalidIntegerError extends Error {
    constructor(...parameters) {
        super(...parameters);

        this.name = "LogInvalidIntegerError";
    }
}

function logInteger(x) {
    if (!Number.isInteger(x)) {
        throw new LogInvalidIntegerError("First argument must be an integer");
    }

    console.log(`Integer: ${x}`);
}

try {
    logInteger(1);
    // Integer: 1

    logInteger(1.2);
    // LogInvalidIntegerError: First argument must be an integer
} catch (error) {
    if (error instanceof LogInvalidIntegerError) {
        console.error("Nope, integers only.");
    } else {
        console.error(`Unhandled error: ${error.toString()}`);
    }
}

Just a suggestion for those that don't know that this kind of behavior exists in JavaScript as well.

This also works in chai with the expect helper.

"use strict";

import "mocha";
import { expect } from "chai";
import { logInteger, LogInvalidIntegerError } from "../src/log.js";

describe("log.js", function() {
    describe("logInteger", function() {
        it("should throw an exception on non-integer", function() {
            expect(log(1.2)).to.throw(LogInvalidIntegerError);
        });
    });
});

Which is kind of cool IMO!

Collapse
 
jamesrweb profile image
James Robb

Hi Amin! I agree, it is a nice thing to do but usually I wouldn't implement my own custom error because if I did that in every project I would have inconsistencies all over the place. Instead I would normally use something like the custom-error npm package to generate custom error types if required. Usually though, even that is something I tend to avoid unless there is a clear requirement to do so.

I also didn't include such an implementation in this post since it is out of scope generally speaking and I wanted the focus to be on the challenge and not surrounding elements or constructs.

Thanks for the input though, it's a good point and I hope this answer was well received.

Collapse
 
aminnairi profile image
Amin

Yay! I didn't know about this package. Looks really interesting. Will dig the source-code when I got some time and... It is added to my todo list. Haha!

Thread Thread
 
jamesrweb profile image
James Robb

Sure, could perhaps be a good open source project to contribute to and tidy up since it is been a while since it was updated although it works perfectly as is for it's usecase now anyway without issues and according to the Snyk vulnerability database when I search for custom-error under npm there are no security vulnerabilities either which is a great thing for any 3rd party package.