restify-errors 模块

github地址:restify-errors

npm地址:restify-errors

一个名为restify-errors的模块公开了许多常见HTTP和REST相关错误的错误构造函数。这些构造器可以与next(err)模式一起使用,以方便地利用服务器的事件发射器。下面是一些例子:

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

server.get('/', function(req, res, next) {
  return next(new errs.ConflictError("I just don't like you"));
});

尝试请求结果:

$ curl -is localhost:3000
HTTP/1.1 409 Conflict
Content-Type: application/json
Content-Length: 53
Date: Fri, 03 Jun 2016 20:29:45 GMT
Connection: keep-alive

{"code":"Conflict","message":"I just don't like you"}

当使用restify-errors时,您也可以直接调用res.send(err),并且restify会自动为您序列化您的错误:

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

server.get('/', function(req, res, next) {
  res.send(new errs.GoneError('gone girl'));
  return next();
});

尝试请求结果:

$ curl -is localhost:8080/
HTTP/1.1 410 Gone
Content-Type: application/json
Content-Length: 37
Date: Fri, 03 Jun 2016 20:17:48 GMT
Connection: keep-alive

{"code":"Gone","message":"gone girl"}

发生这种自动序列化是因为JSON格式化程序将在Error对象上调用JSON.stringify(),并且所有restify-errors都定义了toJSON方法。将此与没有toJSON定义的标准错误对象进行比较:

server.get('/sendErr', function(req, res, next) {
  res.send(new Error('where is my msg?'));
  return next();
});

server.get('/nextErr', function(req, res, next) {
  return next(new Error('where is my msg?'));
});

尝试请求结果:

$ curl -is localhost:8080/sendErr
HTTP/1.1 410 Gone
Content-Type: application/json
Content-Length: 37
Date: Fri, 03 Jun 2016 20:17:48 GMT
Connection: keep-alive

{}

$ curl -is localhost:8080/nextErr
HTTP/1.1 410 Gone
Content-Type: application/json
Content-Length: 37
Date: Fri, 03 Jun 2016 20:17:48 GMT
Connection: keep-alive

{}

如果要使用自定义错误,请确保定义了toJSON,或者使用restify-error的makeConstructor()方法自动创建toJSON支持的错误。

HttpError

restify-errors 提供继承自HttpErrorRestError的构造函数。所有HttpError都有一个数字http状态代码(statusCode)和body属性。状态代码(statusCode)将自动设置HTTP响应状态code,默认情况下的body属性将是消息。

400到5xx之间的所有状态代码自动转换为HttpError,名称为“PascalCase”,并且删除了空格。对于完整的列表,请查看node source

状态码为418: I'm a teapot将会是一个ImATeapotError。

可以参考:HTTP状态码(StatusCode)

RestError

RESTAPI和HTTP的一个常见问题是,它们常常需要重载400和409,以表示一系列不同的东西。对于这些情况下应该做什么,没有真正的标准,但是通常您希望机器能够(安全)解析这些内容,因此restify定义了RestError的约定。RestError是特定HttpError类型之一的子类,并且还使用属性代码和消息将body属性设置为JS对象。例如,这里有一个内置的REST错误:

var errs = require('restify-errors');
var server = restify.createServer();

server.get('/hello/:name', function(req, res, next) {
  return next(new errs.InvalidArgumentError("I just don't like you"));
});

$ curl -is localhost:8080/hello/mark | json
HTTP/1.1 409 Conflict
Content-Type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version
Access-Control-Expose-Headers: Api-Version, Request-Id, Response-Time
Connection: close
Content-Length: 60
Content-MD5: MpEcO5EQFUZ2MNeUB2VaZg==
Date: Tue, 03 Jan 2012 00:50:21 GMT
Server: restify
Request-Id: bda456dd-2fe4-478d-809c-7d159d58d579
Response-Time: 3

{
  "code": "InvalidArgument",
  "message": "I just don't like you"
}

内置的HttpErrors:

  • BadRequestError (400 Bad Request)

  • UnauthorizedError (401 Unauthorized)

  • PaymentRequiredError (402 Payment Required)

  • ForbiddenError (403 Forbidden)

  • NotFoundError (404 Not Found)

  • MethodNotAllowedError (405 Method Not Allowed)

  • NotAcceptableError (406 Not Acceptable)

  • ProxyAuthenticationRequiredError (407 Proxy Authentication Required)

  • RequestTimeoutError (408 Request Time-out)

  • ConflictError (409 Conflict)

  • GoneError (410 Gone)

  • LengthRequiredError (411 Length Required)

  • PreconditionFailedError (412 Precondition Failed)

  • RequestEntityTooLargeError (413 Request Entity Too Large)

  • RequesturiTooLargeError (414 Request-URI Too Large)

  • UnsupportedMediaTypeError (415 Unsupported Media Type)

  • RequestedRangeNotSatisfiableError (416 Requested Range Not Satisfiable)

  • ExpectationFailedError (417 Expectation Failed)

  • ImATeapotError (418 I’m a teapot)

  • UnprocessableEntityError (422 Unprocessable Entity)

  • LockedError (423 Locked)

  • FailedDependencyError (424 Failed Dependency)

  • UnorderedCollectionError (425 Unordered Collection)

  • UpgradeRequiredError (426 Upgrade Required)

  • PreconditionRequiredError (428 Precondition Required)

  • TooManyRequestsError (429 Too Many Requests)

  • RequestHeaderFieldsTooLargeError (431 Request Header Fields Too Large)

  • InternalServerError (500 Internal Server Error)

  • NotImplementedError (501 Not Implemented)

  • BadGatewayError (502 Bad Gateway)

  • ServiceUnavailableError (503 Service Unavailable)

  • GatewayTimeoutError (504 Gateway Time-out)

  • HttpVersionNotSupportedError (505 HTTP Version Not Supported)

  • VariantAlsoNegotiatesError (506 Variant Also Negotiates)

  • InsufficientStorageError (507 Insufficient Storage)

  • BandwidthLimitExceededError (509 Bandwidth Limit Exceeded)

  • NotExtendedError (510 Not Extended)

  • NetworkAuthenticationRequiredError (511 Network Authentication Required)

  • BadDigestError (400 Bad Request)

  • BadMethodError (405 Method Not Allowed)

  • InternalError (500 Internal Server Error)

  • InvalidArgumentError (409 Conflict)

  • InvalidContentError (400 Bad Request)

  • InvalidCredentialsError (401 Unauthorized)

  • InvalidHeaderError (400 Bad Request)

  • InvalidVersionError (400 Bad Request)

  • MissingParameterError (409 Conflict)

  • NotAuthorizedError (403 Forbidden)

  • RequestExpiredError (400 Bad Request)

  • RequestThrottledError (429 Too Many Requests)

  • ResourceNotFoundError (404 Not Found)

  • WrongAcceptError (406 Not Acceptable)

内置的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

您还可以使用makeConstructor方法创建自己的子类:

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

errs.makeConstructor('ZombieApocalypseError');

var myErr = new errs.ZombieApocalypseError('zomg!');

构造函数采用message, statusCode,restCode, 和 context选项。请查看restify-errors仓库查看更多信息。

Last updated

Was this helpful?