Skip to content

angular-package/error

 
 

Repository files navigation

Packages

Useful and simple to use packages based on the angular.io.

Package Description Status
callback Manages the callback function. npm version
change-detection Improves application performance. npm version
component-loader Handles dynamic loading components. npm version
core Core features. npm version
error Manages an Error. npm version
prism Prism highlighter module. npm version
property Handles object properties. npm version
reactive Automatize the process of creating some rxjs features. npm version
testing Support for testing other packages. npm version
type Common types, type guards, and type checkers. npm version
ui User interface. In Progress

Click on the package name to visit its GitHub page.

angular-package/error

Manages an Error.

npm version

GitHub issues GitHub forks GitHub stars GitHub license

GitHub sponsors Support me on Patreon


Table of contents



Basic concepts

Checks

It's to check the provided value to be the same as expected.

Type guard (constrain)

Constrains the parameter type to not let input unexpected value in the code editor.

Guards

It's a combination of both above, constrains the type of the parameter in the code editor, and checks its provided argument.

Defines

Returns defined value from a method of an object.
Defines new value in an object and returns a defined value.

Gets

Returns a value from an object.

Sets

Adds or updates an element with a specified key and a value to an object and returns an object.


Skeleton

This package was built by the library skeleton which was generated with Angular CLI version 12.1.1.

Copy this package to the packages/error folder of the library skeleton then run the commands below.

Build

Run ng build error to build the package. The build artifacts will be stored in the dist/ directory.

Running unit tests

Run ng test error to execute the unit tests via Karma.


Installation

Install @angular-package/error package with command:

npm i @angular-package/error --save

Api

import {
  // Class.
  ValidationError,
  // Interface.
  ErrorMessage,
} from '@angular-package/error';
/*
 * Experimental.
 */
import {
  // Class.
  MessageBuilder,
  MessageBuilderTemplate,
  MessageFunctionBuilder,
} from '@angular-package/error';

ValidationError

Manages an Error of validation.

Static properties:

ValidationError. Description
template: string A template of the error message guarded by a string type with the replaceable [problem] and [fix] words. By default, it's set to 'Problem: [problem] => Fix: [fix]'.

Instance properties:

ValidationError.prototype. Description
fix: string A possible solution to the described problem of validation that is guarded by a string type.
message: string A validation error message guarded by a string type that can be built with the problem and fix of ValidationError on the template by the throw() and setMessage() method.
name: string Error name of a string type that is being thrown.
problem: string Description of a validation problem guarded by a string type.

Static methods:

ValidationError. Description
defineMessage() Defines the validation error message of a string type from the provided message of the ErrorMessage interface.

Constructor:

Constructor Description
ValidationError() Creates a new instance with the message. If the provided message is an object, then its properties are assigned to the instance.

Instance methods:

ValidationError.prototype. Description
setFix() Sets the fix a possible solution to the described problem.
setMessage() Sets the validation error message of a string type from the provided message of the ErrorMessage interface.
setProblem() Sets description problem of a validation.
setTemplate() Sets the template of validation error message.
throw() Throws an error of ValidationError with actual settings.
updateMessage() Updates the message with a stored fix, problem, and template.

ValidationError static properties


ValidationError.template

update

2.0.0: Uses static private property #template and guards the value with private static method #guardTemplate() to be string type that contains [fix] and [problem] words.

A template of the error message guarded by string type with the replaceable [problem] and [fix] words. By default, it's set to Problem: [problem] => Fix: [fix]. It can be set directly or by the setTemplate() and setMessage() method. The value is being checked against the existence of [problem] and [fix] words.

static get template(): string {
  return ValidationError.#template;
}
static set template(value: string) {
  ValidationError.#template = ValidationError.#guardTemplate(value)
    ? value
    : ValidationError.#template;
}

ValidationError instance public properties


ValidationError.prototype.fix

update

2.0.0: Uses static private property #fix and guards the value to be a string type.

A possible solution to the described problem of validation that is guarded by a string type. By default, it's an empty string. It can be set directly or by the setFix() and setMessage() method.

public get fix(): string {
  return this.#fix;
}
public set fix(value: string) {
  this.#fix = guard.string(value) ? value : this.#fix;
}

ValidationError.prototype.message

update

2.0.0: Uses inherited from Error property and guards the value to be a string type.

A validation error message guarded by a string type that can be build from the problem and fix of ValidationError on the template. It can be set directly or by the throw() and setMessage() method.

public set message(value: string) {
  super.message = guard.string(value) ? value : super.message;
}
public get message(): string {
  return super.message;
}

ValidationError.prototype.name

Error name of a string type that is being thrown. By default, it's 'ValidationError'.

public name = ValidationError.name;

ValidationError.prototype.problem

update

Description of a validation problem guarded by a string type. By default, it's an empty string. It can be set directly or by the setProblem() and setMessage() method.

public get problem(): string {
  return this.#problem;
}
public set problem(value: string) {
  this.#problem = guard.string(value) ? value : this.#problem;
}

ValidationError static methods


ValidationError.defineMessage()

update

2.0.0: Adds template to the provided message instead of separate parameter and guards it with a static #guardMessage() method.

Defines the validation error message of a string type from the provided message of the ErrorMessage interface.

// Syntax.
public static defineMessage(
  message: ErrorMessage,
  callback?: ResultCallback<CallbackPayload & ErrorMessage>
): string {
  return ValidationError.#guardMessage(message, callback)
    ? (message.template || ValidationError.template)
        .replace(`[fix]`, message.fix)
        .replace(`[problem]`, message.problem)
    : '';
}

Parameters:

Name: type Description
message: ErrorMessage An object of the ErrorMessage interface to build a message of a string type. The value is checked against the proper object
callback?: ResultCallback An optional callback function of ResultCallback type to handle the check whether the provided message contains required problem and fix properties

Returns:

The return value is a message of a string type created from the provided message of ErrorMessage interface, or it's an empty string if the provided message object isn't proper.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';

/*
  Returns
  --------
  Problem: The problem has no solution. => Fix: There is no solution
  to the described problem.
*/
const errorMessage = ValidationError.defineMessage({ fix, problem });
/*
  Example usage: create an error message of a string type
  from the provided object with a different template.
*/
import { ValidationError } from '@angular-package/error';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';
const template = `[problem] ... [fix]`;

/*
  Returns
  --------
  The problem has no solution. ... There is no solution to the described problem.
*/
const errorMessage = ValidationError.defineMessage({
  fix, problem, template
});
/*
  Example usage: create an error message of a string type
  from the provided object and the changed template.
*/
import { ValidationError } from '@angular-package/error';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';

// Change the template by directly assign a new value.
ValidationError.template = `\nPROBLEM: [problem]\nFIX: [fix] `;

/*
  Returns
  -------
  PROBLEM: The problem has no solution.
  FIX: There is no solution to the described problem. 
*/
const errorMessage = ValidationError.defineMessage({ fix, problem });
/*
  Example usage: create an error message of a string type
  from the provided object and the changed template.
*/
import { ValidationError } from '@angular-package/error';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';

const errorMessage = ValidationError.defineMessage(
  { fix, problem },
  (result, payload) => {
    // Do something with the `result` of the `message` check
    // and `payload`.
    return result;
  }
);

ValidationError constructor


ValidationError()

update

2.0.0: Adds template to the provided message instead of separate parameter and uses a new method setMessage() to set message. Handle the callback for all instance methods with the callback parameter.

Creates a new instance with the message. If the provided message is an object, then its properties are assigned to the instance.

// Syntax.
constructor(
  message: string | ErrorMessage = '',
  callback?: (callback: Callback<VEAllowedCallback>) => void
) {
  super();

  // Sets the callback for an instance methods.
  if (is.function(callback)) {
    callback(this.#callback);
  }

  // Initializes the message and assigns message properties `fix`, `problem` and optionally `template` to a new instance.
  this.setMessage(message);
}

Parameters:

Name: type Description
message: string | ErrorMessage The message of a string type or of an ErrorMessage interface that is used to throw with an Error.
callback?: (callback: Callback<VEAllowedCallback>) => void An optional function to handle the internal instance of Callback.

Returns:

The return value is an instance of ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

const fix = 'There is no solution to the described problem.';
const problem = 'The problem has no solution.';

const validationError = new ValidationError({ fix, problem });
// Example usage with callback.
import { ValidationError } from '@angular-package/error';

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Define a problem.
const problem = 'The problem has no solution.';

// Define a template.
const template = 'PROBLEM: [problem] FIX: [fix]';

// Initialize an instance.
const validationError = new ValidationError(
  { fix, problem, template },
  (callback) => {
    callback
      /*
      Console: false,
      {
        "fix": "There is no solution to the described problem.",
        "problem": "The problem has no solution.",
        "template": "PROBLEM: [problem] FIX: [fix]"
      }

      Console: true,
      {
        "fix": "There is no solution to the described problem.",
        "problem": "The problem has no solution.",
        "template": "PROBLEM: [problem] FIX: [fix]"
      }
    */
      .setResultCallback('setFix', (result, payload) =>
        console.log(`setFix`, result, payload);
      )

      // Console: 'setFix true There is no solution to the described problem.'
      .setResultCallback('setMessage', (result, payload) =>
        console.log(`setMessage`, result, payload);
      )

      // Console: 'setProblem true The problem has no solution.'
      .setResultCallback('setProblem', (result, payload) =>
        console.log(`setProblem`, result, payload);
      )

      // Console: 'setTemplate true PROBLEM: [problem] FIX: [fix]'
      .setResultCallback('setTemplate', (result, payload) =>
        console.log(`setTemplate`, result, payload);
      );
  }
);

ValidationError instance public methods


ValidationError.prototype.setFix()

new

Sets the fix a possible solution to the described problem.

// Syntax.
public setFix(
  fix: string,
  callback: ResultCallback<CallbackPayload> = this.#callback.getCallback(
    'setFix'
  )
): this {
  if (guard.string(fix, callback)) {
    this.#fix = fix;
  }
  return this;
}

Parameters:

Name: type Description
fix: string A possible solution to the described problem guarded by a string type.
callback?: ResultCallback<CallbackPayload> An optional callback function of ResultCallback type to handle the check whether the provided fix is a string. By default, it uses an internal callback under the 'setFix' name, which can be initially set by the optional callback parameter that gives access to the internal instance of Callback.

Returns:

The return value is an instance of an ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Returns 'There is no solution to the described problem.'
validationError.setFix(fix).fix;
// Example usage with a callback.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Set the fix and handle the check of it with a callback.
validationError.setFix(fix, (result, payload) => {
  // Returns `true`.
  result;
  // Returns `There is no solution to the described problem.`.
  payload;
  return result;
});

ValidationError.prototype.setMessage()

new

Sets the validation error message of a string type from the provided message of the ErrorMessage interface.

// Syntax.
public setMessage(
  message: string | ErrorMessage,
  callback: ResultCallback<
    CallbackPayload & ErrorMessage
  > = this.#callback.getCallback('setMessage')
): this {
  this.message = is.string(message, callback)
    ? // Sets a message of a string type from the provided message of `string`.
      message
    : // Sets a message of a string type from the provided message of `ErrorMessage`.
      ValidationError.defineMessage(message, callback);

  // Sets `fix`, `problem` and optionally `template` from the provided `message`.
  if (is.object(message)) {
    this.setFix(message.fix).setProblem(message.problem);
    if (is.defined(message.template)) {
      this.setTemplate(message.template);
    }
  }
  return this;
}

Parameters:

Name: type Description
message: string | ErrorMessage An object of an ErrorMessage interface to build the message of a string type. The value is checked against the proper object.
callback?: ResultCallback<CallbackPayload> An optional callback function of ResultCallback type to handle the check whether the provided message is a string type or whether it's an object that contains required problem and fix properties. By default, it uses an internal callback under the 'setMessage' name, which can be initially set by the optional callback parameter that gives access to the internal instance of Callback.

Returns:

The return value is an instance of an ValidationError.

Usage:

// Example usage with a callback.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Define a problem.
const problem = 'The problem has no solution.';

// Define a template.
const template = 'PROBLEM: [problem], FIX: [fix]';

// Set the message and handle the check of it with a callback.
validationError.setMessage({ fix, problem }, (result, payload) => {
  // Returns `false` then `true`.
  result;
  /*
    Returns {
      "fix": "There is no solution to the described problem.",
      "problem": "The problem has no solution.",
      "template": "PROBLEM: [problem] FIX: [fix]"
    }
  */
  payload;
  return result;
});
/*
  Returns
  PROBLEM: The problem has no solution. FIX: There is no solution to the described problem.
*/
console.log(validationError.message);

ValidationError.prototype.setProblem()

new

Sets description problem of a validation.

public setProblem(
  problem: string,
  callback: ResultCallback<CallbackPayload> = this.#callback.getCallback(
    'setProblem'
  )
): this {
  this.#problem = guard.string(problem, callback) ? problem : this.#problem;
  return this;
}

Parameters:

Name: type Description
problem: string Description of a validation problem guarded by a string type.
callback?: ResultCallback<CallbackPayload> An optional callback function of ResultCallback type to handle the check whether the provided problem is a string. By default, it uses an internal callback under the 'setProblem' name, which can be initially set by the optional callback parameter that gives access to the internal instance of Callback.

Returns:

The return value is an instance of an ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a problem.
const problem = 'The problem has no solution.';

// Returns 'The problem has no solution.'
validationError.setProblem(problem).problem;
// Example usage with a callback.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a problem.
const problem = 'The problem has no solution.';

// Set the problem and handle the check of it with a callback.
validationError.setProblem(problem, (result, payload) => {
  // Returns `true`.
  result;
  // Returns 'The problem has no solution.'
  payload;
  return result;
});

ValidationError.prototype.setTemplate()

new

Sets the template of validation error message.

public setTemplate(
  template: string,
  callback: ResultCallback<CallbackPayload> = this.#callback.getCallback(
    'setTemplate'
  )
): this {
  this.#tpl = ValidationError.#guardTemplate(template, callback)
    ? template
    : this.#tpl;
  return this;
}

Parameters:

Name: type Description
template: string A message template guarded by a string type with replaceable [problem] and [fix] words.
callback?: ResultCallback<CallbackPayload> An optional callback function of ResultCallback type to handle the check whether the provided template is a string that contains [fix] and [problem] words. By default, it uses an internal callback under the 'setTemplate' name, which can be initially set by the optional callback parameter that gives access to the internal instance of Callback.

Returns:

The return value is an instance of an ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a template.
const template = 'PROBLEM: [problem], FIX: [fix]';

// Set the template.
validationError.setTemplate(template);

// Returns 'PROBLEM: [problem], FIX: [fix]'
validationError.template;
// Example usage with a callback.
import { ValidationError } from '@angular-package/error';

// Initialize an instance.
const validationError = new ValidationError();

// Define a template.
const template = 'PROBLEM: [problem], FIX: [fix]';

// Set the template and handle the check of it with a callback.
validationError.setTemplate(template, (result, payload) => {
  // Returns `true`.
  result;
  // Returns 'PROBLEM: [problem], FIX: [fix]'
  payload;
  return result;
});

ValidationError.prototype.throw()

new

Throws an error of ValidationError with the message built from the stored fix, problem and template or optionally from the provided message.

public throw(message?: string | ErrorMessage): void {
  if (is.defined(message)) {
    this.setMessage(message);
  } else {
    this.updateMessage();
  }
  throw this;
}

Parameters:

Name: type Description
message?: string | ErrorMessage An optional object of an ErrorMessage interface to build the message of a string type. The value is checked against the proper object.

Returns:

The return value is an instance of an ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Define a problem.
const problem = 'The problem has no solution.';

// Define a template.
const template = 'PROBLEM: [problem] FIX: [fix]';

// Initialize an instance.
const validationError = new ValidationError({ fix, problem, template });

// Throw an error.
validationError.throw();
// Example usage.
import { ValidationError } from '@angular-package/error';

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Define a problem.
const problem = 'The problem has no solution.';

// Define a template.
const template = 'PROBLEM: [problem] FIX: [fix]';

// Initialize an instance.
const validationError = new ValidationError();

// Throw an error with message.
validationError.throw({ fix, problem, template });

ValidationError.prototype.updateMessage()

new

Updates the message with a stored fix, problem, and template.

public updateMessage(): void {
  this.message = ValidationError.defineMessage({
    fix: this.#fix,
    problem: this.#problem,
    template: this.#tpl,
  });
}

Returns:

The return value is an instance of an ValidationError.

Usage:

// Example usage.
import { ValidationError } from '@angular-package/error';

// Define a fix.
const fix = 'There is no solution to the described problem.';

// Define a problem.
const problem = 'The problem has no solution.';

// Define a template.
const template = 'PROBLEM: [problem] FIX: [fix]';

// Initialize an instance.
const validationError = new ValidationError();

// Sets defined above fix, problem, and template.
validationError.setProblem(problem).setFix(fix).setTemplate(template);

// Returns empty string.
validationError.message;

// Update the message with actual settings.
validationError.updateMessage();

/*
  Returns
  PROBLEM: The problem has no solution. FIX: There is no solution to the described problem.
*/
validationError.message;

// Throw.
validationError.throw();

// or throw
throw validationError;

Another example usage of ValidationError

// Example usage.
import { ValidationError } from '@angular-package/error';

// Declare shape of the person.
interface Person {
  firstName: string;
  lastName: string;
}

// Initialize an instance.
const validationErrorOfPerson = new ValidationError();

// Define a fix.
const fix = 'Please, provide only alphabetical characters.';

// Create an object.
const personError = {
  firstName: validationErrorOfPerson.setMessage({
    problem: 'Provided the first name cannot include special characters.',
    fix
  }),
  lastName: validationErrorOfPerson.setMessage({
    problem: 'Provided the last name cannot include special characters.',
    fix
  })
};


const addPerson = (person: Person) => {
  if (person.firstName.includes('#')) {
    personError.firstName.throw();
  }
  if (person.firstName.includes('#')) {
    personError.lastName.throw();
  }
};

addPerson({
  firstName: '#',
  lastName: '#'
});

Interface

ErrorMessage

update

2.0.0: Adds an optional template property.

The shape of an object for an error message that contains a possible solution to the described problem.

export interface ErrorMessage {
  fix: string;
  problem: string;
  template?: string;
}

Properties:

fix: string
A possible solution to the described problem of a string type.

problem: string
Description of validation problem of a string type.

template?: string
new
An optional error message template of a string type.


Type

VEAllowedCallback

Allowed callback function names available for the ValidationError.

type VEAllowedCallback = 'setFix' | 'setMessage' | 'setProblem' | 'setTemplate';

Experimental

experimental

Message builder

MessageBuilder

Message builder for error message of a string type.

// Example usage of building a function.
import { MessageBuilder } from '@angular-package/error';

/**
 * Initialize `MessageBuilder`.
 */
const messageFunctionBuilder = new MessageBuilder('function');

messageFunctionBuilder
  .setFunctionName('guardString')
  .setParam('value', 'string')
  .setReturn('boolean');

// Console returns `guardString(value: string): boolean`
console.log(messageFunctionBuilder.get);
// Example usage of building a method.
import { MessageBuilder } from '@angular-package/error';

/**
 * Initialize `MessageBuilder`.
 */
const messageMethodBuilder = new MessageBuilder('method');

// Build the method of any class.
messageMethodBuilder
  .setMethodName('setPerson')
  .setParam('value', 'string')
  .setReturn('this');

// Console returns `setPerson(value: string): this`
console.log(messageMethodBuilder.get);
// Example usage of building a class.
import { MessageBuilder } from '@angular-package/error';

/**
 * Initialize `MessageBuilder`.
 */
const messageClassBuilder = new MessageBuilder('class');

// Build the method of a specified class.
messageClassBuilder
  .setClassName('Person.prototype.')
  .setMethodName('setPerson')
  .setParam('value?', 'object')
  .setReturn('object');

// Console returns `Person.prototype.setPerson(value?: object): object`
console.log(messageClassBuilder.get);

MessageFunctionBuilder

Message function builder for error message of a string type.

// Example usage of building a function.
import { MessageFunctionBuilder } from '@angular-package/error';

/**
 * Initialize `MessageFunctionBuilder`.
 */
const messageFunctionBuilder = new MessageFunctionBuilder();

messageFunctionBuilder
  .setName('guardString')
  .setParam('value', 'string')
  .setReturn('boolean')
  .build();

// Console returns `guardString(value: string): boolean`
console.log(messageFunctionBuilder.get);

Changelog

The changelog of this package is based on keep a changelog. To read it, click on the CHANGELOG.md link.

A changelog is a file which contains a curated, chronologically ordered list of notable changes for each version of a project. - keep a changelog


GIT

Commit

Versioning

Semantic Versioning 2.0.0

Given a version number MAJOR.MINOR.PATCH, increment the:

  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality in a backwards-compatible manner, and
  • PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

FAQ How should I deal with revisions in the 0.y.z initial development phase?

The simplest thing to do is start your initial development release at 0.1.0 and then increment the minor version for each subsequent release.

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

License

MIT © angular-package (license)