@0x0/restify-errors 中文文档教程

发布于 6年前 浏览 29 项目主页 更新于 3年前

restify-errors

NPM 版本构建状态覆盖状态依赖状态 开发依赖状态bitHound Score

HTTP 和 REST 错误构造函数的集合。

该模块附带一组构造函数,可用于新建错误 具有默认状态代码的对象。

该模块附带以下 HttpErrors:

  • 400 BadRequestError
  • 401 UnauthorizedError
  • 402 PaymentRequiredError
  • 403 ForbiddenError
  • 404 NotFoundError
  • 405 MethodNotAllowedError
  • 406 NotAcceptableError
  • 407 ProxyAuthenticationRequiredError
  • 408 RequestTimeoutError
  • 409 ConflictError
  • 410 GoneError
  • 411 LengthRequiredError
  • 412 PreconditionFailedError
  • 413 RequestEntityTooLargeError
  • 414 RequesturiTooLargeError
  • 415 UnsupportedMediaTypeError
  • 416 RangeNotSatisfiableError (For Node >= 4 & iojs >= 3)
  • 416 RequestedRangeNotSatisfiableError (For Node 0.x & iojs < 3)
  • 417 ExpectationFailedError
  • 418 ImATeapotError
  • 422 UnprocessableEntityError
  • 423 LockedError
  • 424 FailedDependencyError
  • 425 UnorderedCollectionError
  • 426 UpgradeRequiredError
  • 428 PreconditionRequiredError
  • 429 TooManyRequestsError
  • 431 RequestHeaderFieldsTooLargeError
  • 500 InternalServerError
  • 501 NotImplementedError
  • 502 BadGatewayError
  • 503 ServiceUnavailableError
  • 504 GatewayTimeoutError
  • 505 HttpVersionNotSupportedError
  • 506 VariantAlsoNegotiatesError
  • 507 InsufficientStorageError
  • 509 BandwidthLimitExceededError
  • 510 NotExtendedError
  • 511 NetworkAuthenticationRequiredError

和以下 RestErrors:

  • 400 BadDigestError
  • 405 BadMethodError
  • 500 InternalError
  • 409 InvalidArgumentError
  • 400 InvalidContentError
  • 401 InvalidCredentialsError
  • 400 InvalidHeaderError
  • 400 InvalidVersionError
  • 409 MissingParameterError
  • 403 NotAuthorizedError
  • 412 PreconditionFailedError
  • 400 RequestExpiredError
  • 429 RequestThrottledError
  • 404 ResourceNotFoundError
  • 406 WrongAcceptError

一些状态代码重叠,因为应用程序可以选择最多 适用于给定场景的错误类型和状态代码。 如果你给 场景需要更多自定义的东西,可以自定义错误对象 带有一个选项对象。

Getting Started

安装模块:npm install restify-errors

对于 TypeScript 类型定义:npm install @types/restify-errors

Usage

Migration from 5.x to 6.x

从 6.x 开始,这个模块现在是一个薄包装器这 VError 模块。 每一个错误 该模块暴露的构造函数继承自VError,这意味着 构造函数签名现在也与 VError 相同。

所有 VError 静态方法也在 restify-errors 导出时重新导出 目的。 出于所有意图和目的,您应该将此库视为 VError 的扩展,带有内置构造函数和糖函数的列表。

旧的 5.x 和 6.x API 之间的主要区别是对 选项名称及其提供位置。 在 5.x 中:

const err = new errors.InternalServerError(priorErr, {
    message: 'boom!',
    context: { foo: 'bar' }
});

在 6.x 中:

const err = new errors.InternalServerError({
    cause: priorErr,
    info: { foo: 'bar' }
}, 'boom!');

Context/Info object

在 5.x 中,.context 属性用于存储和捕获有关 导致错误的场景。 这个概念仍然受支持,但现在使用 VError 的信息对象实现了同样的事情。 因为它使用 VError API,所有 您现在必须在创建错误时传递 info 而不是 context

出于迁移目的,通过 .context 访问信息对象将是 通过6.x支持,序列化器也将继续支持它。 两者都可能在未来的版本中被弃用。 要访问信息对象,您可以 使用 VError 静态方法 .info(),它在 restify-errors 导出:

var errors = require('restify-errors');
var verror = require('verror');

var err = new errors.InternalServerError({
    info: {
        foo: 'bar'
    }
});
errors.info(err);  // => { foo: 'bar' }
verror.info(err);  // => { foo: 'bar' }

请注意,直接使用 verror 也可以,因为所有由创建的错误对象 这个库继承自 VError。

Custom constructors

在 5.x 中,使用 makeConstructor 类会将构造函数本身添加到 restify-error 的 module.exports 对象。 这在复杂的情况下是有问题的 应用程序,其中自定义错误构造函数可以跨多个共享 多个上下文中的模块。

因此,在 6.x 中,自定义构造函数不再存储在 module.exports 对象,用户有责任保留一个 引用那些自定义构造函数。

Creating Errors

在您的应用程序中,使用构造函数创建错误:

var errors = require('restify-errors');

server.get('/foo', function(req, res, next) {

    if (!req.query.foo) {
        return next(new errors.BadRequestError());
    }

    res.send(200, 'ok!');
    return next();
});

Checking Error types

您可以轻松地对 Error 对象进行实例检查:

function redirectIfErr(req, res, next) {
    var err = req.data.error;
    if (err) {
        if (err instanceof errors.InternalServerError) {
            next(err);
        } else if (err instanceof errors.NotFoundError) {
            res.redirect('/NotFound', next);
        }
    }
}

您还可以检查 .code.name 属性以防万一有 应用程序进程中的多个 restify-error 副本:

function redirectIfErr(req, res, next) {
    var err = req.data.error;
    if (err) {
        if (err.name === 'InternalServerError' ||
        err.code === 'InternalServer') {
            next(err);
        } else if (err instanceof errors.NotFoundError) {
            res.redirect('/NotFound', next);
        }
    }
}

Serializing Errors

此模块中的所有错误对象都带有 toString()toJSON() 方法。 Restify 使用这些方法在传递给错误时“呈现”错误 res.send()

function render(req, res, next) {
    res.send(new errors.InternalServerError());
    return next();
}

// => restify will render an application/json response with an http 500:
// {
//     code: 'InternalServerError',
//     message: ''
// }

您可以覆盖这些方法中的任何一个来自定义一个序列化 错误。

Customizing Errors

如果您想更改内置错误的状态代码或消息,您可以 将选项对象传递给构造函数:

function render(req, res, next) {
    var myErr = new errors.InvalidVersionError({
        statusCode: 409
    }, 'Version not supported with current query params');

    res.send(myErr);
    return next();
}

// => even though InvalidVersionError has a built-in status code of 400, it
//    has been customized with a 409 status code. restify will now render an
//    application/json response with an http 409:
// {
//     code: 'InvalidVersionError',
//     message: 'Version not supported with current query params'
// }

Passing in prior errors (causes)

WEError 一样,所有构造函数 接受一个 Error 对象作为构建丰富的 Error 对象的第一个参数,并且 堆栈跟踪。 假设先前的文件查找失败并传递了一个错误:

function wrapError(req, res, next) {

    if (req.error) {
        var myErr = new errors.InternalServerError(req.error, 'bad times!');
        return next(myErr);
    }
    return next();
}

这将允许 Error 对象维护先前错误的上下文,从而给出 您可以完全了解导致潜在问题的原因:

console.log(myErr.message);
// => 'bad times!'

console.log(myErr.toString());
// => InternalServerError: bad times!; caused by Error: file lookup failed!

// if you're using Bunyan, you'll get rich stack traces:
bunyanLogger.info(myErr);

InternalServerError: bad times!
    at Object.<anonymous> (/Users/restify/test.js:30:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
Caused by: Error: file lookup failed!
    at Object.<anonymous> (/Users/restify/test.js:29:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Bunyan/Pino support

由于通过 restify-errors 创建的错误继承自 VError,您将摆脱 通过 bunyan 的标准序列化器支持盒子。 如果您正在使用 info 属性,您可以使用 restify-errors 附带的序列化程序:

var bunyan = require('bunyan');
var restifyErrors = require('restify-errors');

var log = bunyan.createLogger({
    name: 'myLogger',
    serializers: {
        err: restifyErrors.bunyanSerializer
    }
});

var err = new restifyErrors.InternalServerError({
    info: {
        foo: 'bar',
        bar: 1
    }
}, 'cannot service this request');

log.error(err, 'oh noes');
[2016-08-31T22:27:13.117Z] ERROR: log/51633 on laptop: oh noes (err.code=InternalServer)
    InternalServerError: cannot service this request! (foo="bar", bar=1)
        at Object.<anonymous> (/restify/test.js:11:11)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3

当然,您可以将其与标准序列化程序集结合使用 bunyan 附带。 还支持 VError 的 MultiError:

var underlyingErr = new Error('boom');
var multiErr = new verror.MultiError([
    new Error('boom'),
    new restifyErrors.InternalServerError({
        cause: underlyingErr,
        info: {
            foo: 'bar',
            baz: 1
        }
    }, 'wrapped')
]);

log.error(multiErr, 'oh noes');
[2016-08-31T22:48:43.244Z] ERROR: logger/55311 on laptop: oh noes
    MultiError 1 of 2: Error: boom
        at Object.<anonymous> (/restify/test.js:16:5)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3
    MultiError 2 of 2: InternalServerError: wrapped (foo="bar", baz=1)
        at Object.<anonymous> (/restify/test.js:17:5)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3
    Caused by: Error: boom
        at Object.<anonymous> (/restify/test.js:14:21)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3

有关构建丰富错误的更多信息,请查看 VError

Customizing the serializer

序列化器也可以定制。 序列化器目前支持 以下选项:

  • options.topLevelFields {Boolean} - if true, serializes all top level fields found on the error object, minus "known" Error/VError fields. This can be useful if errors are created in dependencies that don't use VError or restify-errors to maintain context in an independent object.

例如:

var bunyan = require('bunyan');
var restifyErrors = require('restify-errors');

var log = bunyan.createLogger({
    name: 'myLogger',
    serializers: restifyErrors.bunyanSerializer.create({
        topLevelFields: true
    })
});

var err = new Error('pull!');
err.espresso = 'normale';

log.error(err, 'oh noes!');
[2018-05-22T01:32:25.164Z] ERROR: myLogger/61085 on laptop: oh noes!
    Error: pull! (espresso="normale")
        at Object.<anonymous> (/restify/serializer.js:11:11)
        at Module._compile (module.js:577:32)
        at Object.Module._extensions..js (module.js:586:10)
        at Module.load (module.js:494:32)
        at tryModuleLoad (module.js:453:12)
        at Function.Module._load (module.js:445:3)
        at Module.runMain (module.js:611:10)
        at run (bootstrap_node.js:387:7)
        at startup (bootstrap_node.js:153:9)

Subclassing Errors

您还可以使用提供的方法创建自己的错误子类 makeConstructor() 方法。

errors.makeConstructor('ExecutionError', {
    statusCode: 406,
    failureType: 'motion',
    message: 'my default message'
});
var myErr = new errors.ExecutionError('bad joystick input!');

console.log(myErr instanceof ExecutionError);
// => true

console.log(myErr.message);
// => 'ExecutionError: bad joystick input!'

console.log(myErr.failureType);
// => 'motion'

console.log(myErr.statusCode);
// => 406

console.log(myErr.stack);

ExecutionError: bad joystick input!
    at Object.<anonymous> (/Users/restify/test.js:30:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

API

所有 Error 构造函数都是可变的并接受以下签名,这些签名 与 VError 和 WError 签名。

new Error(sprintf_args…)

new Error(priorErr [, sprintf_args…])

new Error(options [, sprinf_args…])

restify-errors 为最终签名添加了额外的选项:

  • options.restCode {Number} - a description code for your Error. This is used by restify to render an error when it is directly passed to res.send(). By default, it is the name of your error constructor (e.g., the restCode for a BadDigestError is BadDigest).
  • options.statusCode {Number} - an http status code
  • options.toJSON {Function} - override the default toJSON() method
  • options.toString {Function} - override the default toString() method

makeConstructor(name [, defaults])

创建一个自定义的 Error 构造函数,将其添加到现有的 exports 对象中。

  • name {String} - the name of your Error
  • defaults {Object} - an object of default values that will added to the prototype. It is possible to override the default values for restCode, statusCode, toString() and toJSON().

返回: {Constructor}

makeErrFromCode(statusCode [, args…])

使用 http 状态代码创建一个错误对象。 这使用 http 模块的 STATUS_CODES 进行状态代码查找。 因此,这种方便的方法 仅对创建 HttpErrors 有用,对 RestErrors 没有用。

  • statusCode {Number} - an http status code
  • args - arguments to be passed on to the constructor

返回: {Object} 一个错误对象

Contributing

为任何新的或更改的功能添加单元测试。 确保 lint 和 style 检查通过。

要开始贡献,请安装 git pre-push 钩子:

make githooks

在提交之前,运行 prepush 钩子:

make prepush

如果您有样式错误,您可以通过运行自动修复空格问题:

make codestyle-fix

License

版权所有 (c) 2018 Alex Liu

在 MIT 许可下获得许可。

restify-errors

NPM VersionBuild StatusCoverage StatusDependency StatusdevDependency StatusbitHound Score

A collection of HTTP and REST Error constructors.

This module ships with a set of constructors that can be used to new up Error objects with default status codes.

The module ships with the following HttpErrors:

  • 400 BadRequestError
  • 401 UnauthorizedError
  • 402 PaymentRequiredError
  • 403 ForbiddenError
  • 404 NotFoundError
  • 405 MethodNotAllowedError
  • 406 NotAcceptableError
  • 407 ProxyAuthenticationRequiredError
  • 408 RequestTimeoutError
  • 409 ConflictError
  • 410 GoneError
  • 411 LengthRequiredError
  • 412 PreconditionFailedError
  • 413 RequestEntityTooLargeError
  • 414 RequesturiTooLargeError
  • 415 UnsupportedMediaTypeError
  • 416 RangeNotSatisfiableError (For Node >= 4 & iojs >= 3)
  • 416 RequestedRangeNotSatisfiableError (For Node 0.x & iojs < 3)
  • 417 ExpectationFailedError
  • 418 ImATeapotError
  • 422 UnprocessableEntityError
  • 423 LockedError
  • 424 FailedDependencyError
  • 425 UnorderedCollectionError
  • 426 UpgradeRequiredError
  • 428 PreconditionRequiredError
  • 429 TooManyRequestsError
  • 431 RequestHeaderFieldsTooLargeError
  • 500 InternalServerError
  • 501 NotImplementedError
  • 502 BadGatewayError
  • 503 ServiceUnavailableError
  • 504 GatewayTimeoutError
  • 505 HttpVersionNotSupportedError
  • 506 VariantAlsoNegotiatesError
  • 507 InsufficientStorageError
  • 509 BandwidthLimitExceededError
  • 510 NotExtendedError
  • 511 NetworkAuthenticationRequiredError

and the following RestErrors:

  • 400 BadDigestError
  • 405 BadMethodError
  • 500 InternalError
  • 409 InvalidArgumentError
  • 400 InvalidContentError
  • 401 InvalidCredentialsError
  • 400 InvalidHeaderError
  • 400 InvalidVersionError
  • 409 MissingParameterError
  • 403 NotAuthorizedError
  • 412 PreconditionFailedError
  • 400 RequestExpiredError
  • 429 RequestThrottledError
  • 404 ResourceNotFoundError
  • 406 WrongAcceptError

Some of the status codes overlap, since applications can choose the most applicable error type and status code for a given scenario. Should your given scenario require something more customized, the Error objects can be customized with an options object.

Getting Started

Install the module with: npm install restify-errors

For TypeScript type definitions: npm install @types/restify-errors

Usage

Migration from 5.x to 6.x

As of 6.x this module is now a thin wrapper over the VError module. Every Error constructor exposed by this module inherits from VError, which means the constructor signatures are now also identical to VError.

All VError static methods are also re-exported on the restify-errors export object. For all intents and purposes, you should treat this library as an extension of VError, with a list of built in constructors and sugar functions.

The primary difference between the old 5.x and 6.x API is a reshuffling of the option names and where they are provided. In 5.x:

const err = new errors.InternalServerError(priorErr, {
    message: 'boom!',
    context: { foo: 'bar' }
});

In 6.x:

const err = new errors.InternalServerError({
    cause: priorErr,
    info: { foo: 'bar' }
}, 'boom!');

Context/Info object

In 5.x, the .context property was used to store and capture context about the scenario causing the error. This concept is still supported, but now uses VError's info object to achieve the same thing. As it uses the VError APIs, all you have to now is pass info instead of context when creating an Error.

For migration purposes, accessing the info object via .context will be supported through 6.x, and the serializer will also continue to support it. Both may be deprecated in future versions. To access the info object, you can use the VError static method .info(), which is re-exported on the restify-errors exports:

var errors = require('restify-errors');
var verror = require('verror');

var err = new errors.InternalServerError({
    info: {
        foo: 'bar'
    }
});
errors.info(err);  // => { foo: 'bar' }
verror.info(err);  // => { foo: 'bar' }

Note that using verror directly also works, since all Error objects created by this library inherit from VError.

Custom constructors

In 5.x, using the makeConstructor class would add the constructor itself to restify-error's module.exports object. This was problematic in complex applications, where custom Error constructors could be shared across multiple modules in multiple contexts.

As a result, in 6.x, custom constructors are no longer stored on the module.exports object, and it is the user's responsibility to retain a reference to those custom constructors.

Creating Errors

In your application, create errors by using the constructors:

var errors = require('restify-errors');

server.get('/foo', function(req, res, next) {

    if (!req.query.foo) {
        return next(new errors.BadRequestError());
    }

    res.send(200, 'ok!');
    return next();
});

Checking Error types

You can easily do instance checks against the Error objects:

function redirectIfErr(req, res, next) {
    var err = req.data.error;
    if (err) {
        if (err instanceof errors.InternalServerError) {
            next(err);
        } else if (err instanceof errors.NotFoundError) {
            res.redirect('/NotFound', next);
        }
    }
}

You can also check against the .code or .name properties in case there are multiple copies of restify-error in your application process:

function redirectIfErr(req, res, next) {
    var err = req.data.error;
    if (err) {
        if (err.name === 'InternalServerError' ||
        err.code === 'InternalServer') {
            next(err);
        } else if (err instanceof errors.NotFoundError) {
            res.redirect('/NotFound', next);
        }
    }
}

Serializing Errors

All Error objects in this module ship with both a toString() and toJSON() methods. Restify uses these methods to "render" errors when they are passed to res.send():

function render(req, res, next) {
    res.send(new errors.InternalServerError());
    return next();
}

// => restify will render an application/json response with an http 500:
// {
//     code: 'InternalServerError',
//     message: ''
// }

You can override either of these methods to customize the serialization of an error.

Customizing Errors

If you'd like to change the status code or message of a built-in Error, you can pass an options object to the constructor:

function render(req, res, next) {
    var myErr = new errors.InvalidVersionError({
        statusCode: 409
    }, 'Version not supported with current query params');

    res.send(myErr);
    return next();
}

// => even though InvalidVersionError has a built-in status code of 400, it
//    has been customized with a 409 status code. restify will now render an
//    application/json response with an http 409:
// {
//     code: 'InvalidVersionError',
//     message: 'Version not supported with current query params'
// }

Passing in prior errors (causes)

Like WError, all constructors accept an Error object as the first argument to build rich Error objects and stack traces. Assume a previous file lookup failed and an error was passed on:

function wrapError(req, res, next) {

    if (req.error) {
        var myErr = new errors.InternalServerError(req.error, 'bad times!');
        return next(myErr);
    }
    return next();
}

This will allow Error objects to maintain context from previous errors, giving you full visibility into what caused an underlying issue:

console.log(myErr.message);
// => 'bad times!'

console.log(myErr.toString());
// => InternalServerError: bad times!; caused by Error: file lookup failed!

// if you're using Bunyan, you'll get rich stack traces:
bunyanLogger.info(myErr);

InternalServerError: bad times!
    at Object.<anonymous> (/Users/restify/test.js:30:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3
Caused by: Error: file lookup failed!
    at Object.<anonymous> (/Users/restify/test.js:29:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Bunyan/Pino support

Since errors created via restify-errors inherit from VError, you'll get out of the box support via bunyan's standard serializers. If you are using the info property, you can use the serializer shipped with restify-errors:

var bunyan = require('bunyan');
var restifyErrors = require('restify-errors');

var log = bunyan.createLogger({
    name: 'myLogger',
    serializers: {
        err: restifyErrors.bunyanSerializer
    }
});

var err = new restifyErrors.InternalServerError({
    info: {
        foo: 'bar',
        bar: 1
    }
}, 'cannot service this request');

log.error(err, 'oh noes');
[2016-08-31T22:27:13.117Z] ERROR: log/51633 on laptop: oh noes (err.code=InternalServer)
    InternalServerError: cannot service this request! (foo="bar", bar=1)
        at Object.<anonymous> (/restify/test.js:11:11)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3

You can, of course, combine this with the standard set of serializers that bunyan ships with. VError's MultiError is also supported:

var underlyingErr = new Error('boom');
var multiErr = new verror.MultiError([
    new Error('boom'),
    new restifyErrors.InternalServerError({
        cause: underlyingErr,
        info: {
            foo: 'bar',
            baz: 1
        }
    }, 'wrapped')
]);

log.error(multiErr, 'oh noes');
[2016-08-31T22:48:43.244Z] ERROR: logger/55311 on laptop: oh noes
    MultiError 1 of 2: Error: boom
        at Object.<anonymous> (/restify/test.js:16:5)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3
    MultiError 2 of 2: InternalServerError: wrapped (foo="bar", baz=1)
        at Object.<anonymous> (/restify/test.js:17:5)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3
    Caused by: Error: boom
        at Object.<anonymous> (/restify/test.js:14:21)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
        at Function.Module._load (module.js:300:12)
        at Function.Module.runMain (module.js:441:10)
        at startup (node.js:139:18)
        at node.js:974:3

For more information about building rich errors, check out VError.

Customizing the serializer

The serializer can also be customized. The serializer currently supports the following options:

  • options.topLevelFields {Boolean} - if true, serializes all top level fields found on the error object, minus "known" Error/VError fields. This can be useful if errors are created in dependencies that don't use VError or restify-errors to maintain context in an independent object.

For example:

var bunyan = require('bunyan');
var restifyErrors = require('restify-errors');

var log = bunyan.createLogger({
    name: 'myLogger',
    serializers: restifyErrors.bunyanSerializer.create({
        topLevelFields: true
    })
});

var err = new Error('pull!');
err.espresso = 'normale';

log.error(err, 'oh noes!');
[2018-05-22T01:32:25.164Z] ERROR: myLogger/61085 on laptop: oh noes!
    Error: pull! (espresso="normale")
        at Object.<anonymous> (/restify/serializer.js:11:11)
        at Module._compile (module.js:577:32)
        at Object.Module._extensions..js (module.js:586:10)
        at Module.load (module.js:494:32)
        at tryModuleLoad (module.js:453:12)
        at Function.Module._load (module.js:445:3)
        at Module.runMain (module.js:611:10)
        at run (bootstrap_node.js:387:7)
        at startup (bootstrap_node.js:153:9)

Subclassing Errors

You can also create your own Error subclasses by using the provided makeConstructor() method.

errors.makeConstructor('ExecutionError', {
    statusCode: 406,
    failureType: 'motion',
    message: 'my default message'
});
var myErr = new errors.ExecutionError('bad joystick input!');

console.log(myErr instanceof ExecutionError);
// => true

console.log(myErr.message);
// => 'ExecutionError: bad joystick input!'

console.log(myErr.failureType);
// => 'motion'

console.log(myErr.statusCode);
// => 406

console.log(myErr.stack);

ExecutionError: bad joystick input!
    at Object.<anonymous> (/Users/restify/test.js:30:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

API

All Error constructors are variadic and accept the following signatures, which are identical to the VError and WError signatures.

new Error(sprintf_args…)

new Error(priorErr [, sprintf_args…])

new Error(options [, sprinf_args…])

restify-errors adds additional options for the final signature:

  • options.restCode {Number} - a description code for your Error. This is used by restify to render an error when it is directly passed to res.send(). By default, it is the name of your error constructor (e.g., the restCode for a BadDigestError is BadDigest).
  • options.statusCode {Number} - an http status code
  • options.toJSON {Function} - override the default toJSON() method
  • options.toString {Function} - override the default toString() method

makeConstructor(name [, defaults])

Creates a custom Error constructor, adds it to the existing exports object.

  • name {String} - the name of your Error
  • defaults {Object} - an object of default values that will added to the prototype. It is possible to override the default values for restCode, statusCode, toString() and toJSON().

Returns: {Constructor}

makeErrFromCode(statusCode [, args…])

Create an Error object using an http status code. This uses http module's STATUS_CODES to do the status code lookup. Thus, this convenience method is useful only for creating HttpErrors, and not RestErrors.

  • statusCode {Number} - an http status code
  • args - arguments to be passed on to the constructor

Returns: {Object} an Error object

Contributing

Add unit tests for any new or changed functionality. Ensure that lint and style checks pass.

To start contributing, install the git pre-push hooks:

make githooks

Before committing, run the prepush hook:

make prepush

If you have style errors, you can auto fix whitespace issues by running:

make codestyle-fix

License

Copyright (c) 2018 Alex Liu

Licensed under the MIT license.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文