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: BadRequest
  • 401: Unauthorized
  • 402: PaymentRequired
  • 403: Forbidden
  • 404: NotFound
  • 405: MethodNotAllowed
  • 406: NotAcceptable
  • 407: ProxyAuthenticationRequired
  • 408: RequestTimeout
  • 409: Conflict
  • 410: Gone
  • 411: LengthRequired
  • 412: PreconditionFailed
  • 413: RequestEntityTooLarge
  • 414: RequestURITooLarge
  • 415: UnsupportedMediaType
  • 416: RequestedRangenotSatisfiable
  • 417: ExpectationFailed
  • 418: ImATeapot
  • 421: MisdirectedRequest
  • 422: UnprocessableEntity
  • 423: Locked
  • 424: FailedDependency
  • 426: UpgradeRequired
  • 428: PreconditionRequired
  • 429: TooManyRequests
  • 431: RequestHeaderFieldsTooLarge
  • 500: InternalServerError
  • 501: NotImplemented
  • 502: BadGateway
  • 503: ServiceUnavailable
  • 504: GatewayTimeOut
  • 505: HTTPVersionNotSupported
  • 506: VariantAlsoNegotiates
  • 507: InsufficientStorage
  • 508: LoopDetected
  • 510: NotExtended
  • 511: NetworkAuthenticationRequired