1.2.0 • Published 1 year ago
kodederror v1.2.0
KodedError
This library provides a simple class which extends the javascript Error function to provide an additional code parameter.
Application can then define all the error codes in a JSON file and import them on start up. The error strings are easy to translate or change without needing to modify the source code. Errors output to the log are easily identified by finding the definition and tracing that in the code.
Example Usage
npm install kodederror
Create an 'errorcodes.json' in the project folder:
{
"EXAMPLES":
{
"ERROR": {"code":"EX-ER-001", "message":"This is an example koded error"}
}
}
Then in code
const KodedError = require("kodederror");
const ErrorCodes = require("./errorcodes.json");
function example()
{
return new Promise((resolve, reject) =>
{
reject(new KodedError(ErrorCodes.EXAMPLES.ERROR));
});
}
example().catch((err) => { console.log(err.toString()); });
Will output:
EX-ER-001: Error: My example error
Dynamic Content
For some event strings the application will need to return specific key values, to achieve this the error can be defined with dynamic string markers, like this:
{
"EXAMPLES":
{
"DYNAMIC": {"code":"EX-DY-001", "message":"This value, $VALUE$, will be replaced dynamically"}
}
}
Then in code:
const KodedError = require("kodederror");
const ErrorCodes = require("./errorcodes.json");
function example()
{
return new Promise((resolve, reject) =>
{
reject(new KodedError(ErrorCodes.EXAMPLES.DYNAMIC, {"VALUE":123456}));
});
}
example().catch((err) => { console.log(err.toString()); });
Will output:
EX-DY-001: Error: This value, 123456, will be replaced dynamically