🚨 Fail with an Error object and a conventional code property.
const{ failure,INVALID}=require('@studio/fail');functionread(filename,callback){if(!filename){// Easily fail with a conventional error:throwfailure('Missing filename',INVALID);}// ...}constfs=require('fs');const{ fail, then,INVALID}=require('@studio/fail');functionread(filename,callback){if(!filename){// Easily fail with a conventional error:fail(callback,'Missing filename',INVALID);return;}// Wrap callbacks with and error handling, guarding from multiple invocations:fs.readFile(filename,'utf8',then(callback,(content)=>{// Non-undefined return value is passed to callback:returncontent.trim();}));}Errors should always have a code property with an uppercase error code. To
simplify error handling, use the provided fail utility function and code
constants.
Error codes follow these conventions:
- Fatal errors should have an error code starting with
E_. This is the asynchronous equivalent tothrow. The providedmessageis not supposed to be shown to the user. - Other error codes have no prefix and are not considered fatal, for example a
validation error. The provided
messagemay be shown to the user. - If no
codeproperty is provided, it defaults toE_FAILED.
The provided error codes can be handled generically. You may define additional error codes as needed.
❯ npm i @studio/failfailure(message[, cause][, code[, properties]]): Create anErrorwith the given message andcauseandcodeandproperties. If nocodeis provided it defaults toE_FAILED. Thecausemust be an error object.fail(callback, message[, cause][, code[, properties]]): Creates a failure and invoked the givencallbackwith it.isFatal(error): Whether the given error has acodeproperty the starts withE_or has nocodeproperty.then(callback, next): Create a callback function that invokescallback(err)if an error occurred andnext(result)on success. Throws if the function is invoked more than once with error codeE_FAILEDanderras the cause. Ifnextreturns a non-undefined value, thecallbackis invoked with that result.
E_FAILED: Fatal error.INVALID: Invalid or missing argument or parameter.FORBIDDEN: User is not allowed to access.NOT_FOUND: Resource does not exist.
Throwing errors:
const{ failure,INVALID}=require('@studio/fail');// Fail with a message:throwfailure('Oups!');// The previous is the same as this:throwfailure('Oups!',E_FAILED);// Fail with `code` INVALID:throwfailure('Oups!',INVALID);// Fail with a `cause`:constcause=newError();throwfailure('Oups!',cause);// Fail with a `cause` and `code` INVALID:throwfailure('Oups!',cause,INVALID);// Fail with `properties` and `code` INVALID:throwfailure('Oups!',INVALID,{some: 42});Invoking callbacks with errors:
const{ fail,FORBIDDEN}=require('@studio/fail');fail(callback,'Oups!',FORBIDDEN);- 👻 Studio Log is a tiny ndjson logger that is
codeandcauseaware. - 📦 Studio Changes is used to create the changelog for this module.
MIT
Made with ❤️ on 🌍