Sharp-Error-Handler
A NodeJS module that integrates with HapiJS Server Framework & uses Boom to return custom error messages, error codes & custom error fields.
First define a json object containing where the key is the error name, value is an object containing the required statusCode & message (you may use also use extraFields
Then create your custom error objects
const errorHandler = ;const ServerErrors = errorHandler;
Then inside your code
throw ;
and in the catch function
catcherror return errorHandler;
This makes Hapi Server returns
Features
-
wrapError
function takes two arguments, the first is a log class & the second is the error object itself. the module calls the log function of the first argument, this is helpful if your server uses a default logging library like winston. You can also provide theconsole
class -
Some modules use logging with tag, example
classThen you can use the other function which is
wrapErrorWithTag
which takes three arguments.loggerClass
,tag
,error
-
The arrangement of arguments is made this way to facilitate the usage of
curry
functions. -
a flag called
isCreatedServerError
is added on the error object if the user needs to know whether the error was thrown on purpose or notconst wrappedError = errorHandler;console; //true if the error was created by errorHandler.createServerErrors -
Error names are defaulted to first letter capital example: if errors.json is
Then the error will to throw will be
ServerErrors -
If data is provided in the constructor object of the error it will be added by default to the error message example: if errors.json is
and the error is
throw "122";The message returned will be
"This Id is invalid: 122"
extraFields:
-
adds all keyValue pairs written inside it to the default output object of Hapi
-
must be an object
-
example:
errors.json
Hapi final result will be