Module: Twirbet::Error

Extended by:
T::Sig
Defined in:
lib/twirbet/errors.rb

Constant Summary collapse

CODE_MAP =
T.let({
  "canceled" => CanceledError,
  "unknown" => UnknownError,
  "invalid_argument" => InvalidArgumentError,
  "malformed" => MalformedError,
  "deadline_exceeded" => DeadlineExceededError,
  "not_found" => NotFoundError,
  "bad_route" => BadRouteError,
  "already_exists" => AlreadyExistsError,
  "permission_denied" => PermissionDeniedError,
  "unauthenticated" => UnauthenticatedError,
  "resource_exhausted" => ResourceExhaustedError,
  "failed_precondition" => FailedPreconditionError,
  "aborted" => AbortedError,
  "out_of_range" => OutOfRangeError,
  "unimplemented" => UnimplementedError,
  "internal" => InternalError,
  "unavailable" => UnavailableError,
  "data_loss" => DataLossError,
}.freeze, T::Hash[String, T.class_of(BaseError)])

Class Method Summary collapse

Class Method Details

.build(code, message) ⇒ Object



370
371
372
# File 'lib/twirbet/errors.rb', line 370

def build(code, message)
  CODE_MAP.fetch(code, UnknownError).new(message)
end

.from_exception(exception) ⇒ Object



349
350
351
352
353
354
355
356
# File 'lib/twirbet/errors.rb', line 349

def from_exception(exception)
  case exception
  when BaseError
    exception
  else
    InternalError.new(exception.message)
  end
end

.from_hash(hash) ⇒ Object



365
366
367
# File 'lib/twirbet/errors.rb', line 365

def from_hash(hash)
  build(hash.fetch("code", "unknown"), hash.fetch("msg", ""))
end

.from_intermidate(status, reason, body) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/twirbet/errors.rb', line 335

def from_intermidate(status, reason, body)
  code = case status
  when 400 then "internal"
  when 401 then "unauthenticated"
  when 403 then "permission_denied"
  when 404 then "bad_route"
  when 429, 502, 503, 504 then "unavailable"
  else "unknown"
  end

  build(code, code)
end

.from_json(json) ⇒ Object



359
360
361
362
# File 'lib/twirbet/errors.rb', line 359

def from_json(json)
  hash = JSON.parse(json)
  from_hash(hash)
end

.from_response(response) ⇒ Object



328
329
330
331
332
# File 'lib/twirbet/errors.rb', line 328

def from_response(response)
  from_json(response.body)
rescue JSON::ParserError
  from_intermidate(response.status, "Response is not JSON.", response.body)
end