Skip to content
master
Go to file
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
lib
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

egg-errors

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Errors for Egg.js.

egg-errors provide two kinds of errors that is Error and Exception.

  • Exception is system error that egg will log an error and throw exception, but it will be catched by onerror plugin.
  • Error is business error that egg will transform it to response.

Install

$ npm i egg-errors --save

Usage

Create an Error

const { EggError, EggException } = require('egg-errors');
let err = new EggError('egg error');
console.log(EggError.getType(err)); // ERROR

Create an Exception

err = new EggException('egg exception');
console.log(EggException.getType(err)); // EXCEPTION

You can import an error from an normal error object

err = new Error('normal error');
console.log(EggError.getType(err)); // BUILTIN
err = EggError.from(err);
console.log(EggError.getType(err)); // ERROR

Customize Error

Error can be extendable.

const { EggBaseError } = require('egg-errors');

class CustomError extends EggBaseError {
  constructor(message) {
    super({ message, code: 'CUSTOM_CODE' });
  }
 }

or using typescript you can customize ErrorOptions.

import { EggBaseError, ErrorOptions } from 'egg-errors';

class CustomErrorOptions extends ErrorOptions {
  public data: object;
}
class CustomError extends EggBaseError<CustomErrorOptions> {
  public data: object;
  protected options: CustomErrorOptions;

  constructor(options?: CustomErrorOptions) {
    super(options);
    this.data = this.options.data;
  }
}

Recommand use message instead of options in user land that it can be easily understood by developer, see http error.

HTTP Errors

HTTP Errors is BUILTIN errors that transform 400 ~ 500 status code to error objects. HttpError extends EggBaseError providing two properties which is status and headers;

const { ForbiddenError } = require('egg-errors');
const err = new ForbiddenError('your request is forbidden');
console.log(err.status); // 403

Support short name too:

const { E403 } = require('egg-errors');
const err = new E403('your request is forbidden');
console.log(err.status); // 403

Available Errors

BaseError
|- EggBaseError
|  |- EggError
|  |- HttpError
|  |  |- NotFoundError, alias to E404
|  |  `- ...
|  `- CustomError
`- EggBaseException
   |- EggException
   `- CustomException

Questions & Suggestions

Please open an issue here.

License

MIT

You can’t perform that action at this time.