Error handlingΒΆ
To report errors back to a client of your Service
, simply
throw an instance of the appropriate HttpError
subclass.
For example, the following will produce an HTTP 400
error (Bad Request) if
no request body is present when posting to either the /hello
or /goodbye
endpoints:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | var carbon = require('carbon-io')
var __ = carbon.fibers.__(module)
var o = carbon.atom.o(module)
__(function() {
module.exports = o.main({
_type: carbon.carbond.Service,
port: 8888,
endpoints: {
hello: o({
_type: carbon.carbond.Endpoint,
post: function(req) {
if (Object.keys(req.body).length === 0) {
throw new carbon.HttpErrors.BadRequest("Must supply a body")
}
return { msg: "Hello World! " + carbon.ejson.stringify(req.body) }
}
}),
goodbye: o({
_type: carbon.carbond.Endpoint,
post: function(req) {
if (Object.keys(req.body).length === 0) {
throw new (this.getService().errors.BadRequest)("Must supply a body")
}
return { msg: "Goodbye World! " + carbon.ejson.stringify(req.body) }
}
})
}
})
})
|
Note, all HTTP errors can be referenced via the HttpErrors
property of the
carbon-io
module or via the errors
property of
your Service
definition.
Supported HTTP errors
400
: BadRequest401
: Unauthorized402
: PaymentRequired403
: Forbidden404
: NotFound405
: MethodNotAllowed406
: NotAcceptable407
: ProxyAuthenticationRequired408
: RequestTimeout409
: Conflict410
: Gone411
: LengthRequired412
: PreconditionFailed413
: RequestEntityTooLarge414
: RequestURITooLarge415
: UnsupportedMediaType416
: RequestedRangenotSatisfiable417
: ExpectationFailed418
: ImATeapot421
: MisdirectedRequest422
: UnprocessableEntity423
: Locked424
: FailedDependency426
: UpgradeRequired428
: PreconditionRequired429
: TooManyRequests431
: RequestHeaderFieldsTooLarge500
: InternalServerError501
: NotImplemented502
: BadGateway503
: ServiceUnavailable504
: GatewayTimeOut505
: HTTPVersionNotSupported506
: VariantAlsoNegotiates507
: InsufficientStorage508
: LoopDetected510
: NotExtended511
: NetworkAuthenticationRequired