@golemio/errors
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.1 • Public • Published

    Golemio Errors Library

    Minimal package with custom Error class extending the native built-in JavaScript Error class, providing extra functionality and more capabilities for error handling.

    Trying to adhere to Node.js best practices.

    Developed by http://operatorict.cz

    Prerequisites

    Installation

    Install Node

    Install all npm modules using command:

    yarn
    

    Compilation of typescript code

    To compile typescript code into js one-time

    yarn run build
    

    or run this, to watch all changes

    yarn run build-watch
    

    from the application's root directory.

    Usage

    In your project's package.json set dependency to Errors

    npm install @golemio/errors --save
    
    or
    
    yarn add @golemio/errors --save
    

    Then import module, e.g.

    import { CustomError } from "@golemio/errors";
    

    Our CustomError has:

    • whole stack trace of original Error
    • extends (thus is the type of) Error
    • extra info about origin class
    • extra info about error code
    • distinguishes between operational errors (application error, app knows how to handle it) and fatal errors (app should gracefully die)
    • string message (== only thing the native Error has)

    You can use CustomError class as you would a standard JavaScript Error, you will just get additional info and more capabilities:

    const found = await this.model.findOne(id);
    if (!found ) {
        throw new CustomError("Id `" + id + "` not found", true, "MyModelClass", 404);
    }
    

    you can add the underlying Error to get the whole stack trace:

    try {
        const q = this.model.find("nonsense");
        return await q.exec();
    } catch (err) {
        throw new CustomError("Database error", true, "MyModelClass", 500, err);
    }
    

    and the result you will get:

    "MyModelClass" [500] Database error (ObjectParameterError: Parameter "filter" to find() must be an object, got nonsense)
    CustomError: Database error
        at MyModel.<anonymous> ({path}\src\core\models\MyModel.ts:65:19)
        at Generator.throw (<anonymous>)
        at rejected ({path}\src\core\models\MyModel.ts:5:65)
        at process._tickCallback (internal/process/next_tick.js:68:7)
    

    if you call .toString() on the error object in the error handler (or if you use our ErrorHandler class).

    You can import the error handler function:

    import { handleError } from "@golemio/errors";
    

    The handle function provides a central point for error handling in your application. It logs the error, kills the application if it's unknown non-operational (programmer) error. Returns "API response ready" object if it's a known operational error with one of the standard HTTP codes.

    You can use it:

    try {
        await functionThatThrowsCustomError();      // Can throw our CustomError class
        await jsBuiltInFunction();                  // Can throw a native built-in JavaScript Error
    } catch (err) {                                 // Catches everything
        handleError(err);                           // Handles everything
    }
    

    or for example in Express error handler route

    // Error handler to catch all errors sent by routers (propagated through next(err))
    this.express.use((err: any, req: Request, res: Response, next: NextFunction) => {
        handleError(err).then((error) => {
            if (error) {
                log.silly("Error caught by the router error handler.");
                res.status(error.error_status || 500).send(error);
            }
        });
    });
    

    and the result can be i.e.:

    {
        error_message: "Not Found.",
        error_status: 404
    }
    

    or in development environment (NODE_ENV set to "development"):

    {
        "error_message": "Not Found.",
        "error_status": 404,
        "stack_trace": "CustomError: Id `nonsense` not found\n
        at MyModel.<anonymous> ({path}y\\dist\\core\\models\\MyModel.js:116:23)\n
        at Generator.next (<anonymous>)\n
        at fulfilled ({path}\\dist\\core\\models\\MyModel.js:4:58)\n
        at process._tickCallback (internal/process/next_tick.js:68:7)"
    }
    

    Logging

    Logging uses Winston for standard logging with levels and debug (https://www.npmjs.com/package/debug) for debugging.

    All logs with silly and debug level are printed as standard log (if appropriate log level is set) using Winston as well as using debug module with "golemio:errors" settings.

    You can set both LOG_LEVEL and DEBUG settings in ENV variables.

    Documentation

    For generating documentation run yarn run generate-docs. TypeDoc source code documentation is located in docs/typedoc.

    Contribution guidelines

    Please read CONTRIBUTING.md.

    Troubleshooting

    Contact benak@operatorict.cz or vycpalek@operatorict.cz

    Keywords

    none

    Install

    npm i @golemio/errors

    DownloadsWeekly Downloads

    149

    Version

    1.0.1

    License

    MIT

    Unpacked Size

    38.5 kB

    Total Files

    21

    Last publish

    Collaborators

    • sinacek
    • benaktom
    • vlasaty
    • oict-robot
    • asciidan