Skip to content

Introduced the exceptions module #296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Unreleased

-
- [added] Added the new `firebase_admin.exceptions` module containing the
base exception types and global error codes.
- [changed] Updated the `firebase_admin.instance_id` module to use the new
shared exception types. The type `instance_id.ApiCallError` was removed.

# v2.17.0

Expand Down
48 changes: 48 additions & 0 deletions firebase_admin/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,22 @@

"""Internal utilities common to all modules."""

import requests

import firebase_admin
from firebase_admin import exceptions


_STATUS_TO_EXCEPTION_TYPE = {
400: exceptions.InvalidArgumentError,
401: exceptions.UnauthenticatedError,
403: exceptions.PermissionDeniedError,
404: exceptions.NotFoundError,
409: exceptions.ConflictError,
429: exceptions.ResourceExhaustedError,
500: exceptions.InternalError,
503: exceptions.UnavailableError,
}


def _get_initialized_app(app):
Expand All @@ -33,3 +48,36 @@ def _get_initialized_app(app):
def get_app_service(app, name, initializer):
app = _get_initialized_app(app)
return app._get_service(name, initializer) # pylint: disable=protected-access

def handle_requests_error(error, message=None, status=None):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please document this method, especially what error and status are. It's not clear whether status is an http status code or a grpc status code, for example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

"""Constructs a ``FirebaseError`` from the given requests error.

Args:
error: An error raised by the reqests module while making an HTTP call.
message: A message to be included in the resulting ``FirebaseError`` (optional). If not
specified the string representation of the ``error`` argument is used as the message.
status: An HTTP status code that will be used to determine the resulting error type
(optional). If not specified the HTTP status code on the error response is used.

Returns:
FirebaseError: A ``FirebaseError`` that can be raised to the user code.
"""
if isinstance(error, requests.exceptions.Timeout):
return exceptions.DeadlineExceededError(
message='Timed out while making an API call: {0}'.format(error),
cause=error)
elif isinstance(error, requests.exceptions.ConnectionError):
return exceptions.UnavailableError(
message='Failed to establish a connection: {0}'.format(error),
cause=error)
elif error.response is None:
return exceptions.UnknownError(
message='Unknown error while making a remote service call: {0}'.format(error),
cause=error)

if not status:
status = error.response.status_code
if not message:
message = str(error)
err_type = _STATUS_TO_EXCEPTION_TYPE.get(status, exceptions.UnknownError)
return err_type(message=message, cause=error, http_response=error.response)
182 changes: 182 additions & 0 deletions firebase_admin/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Firebase Exceptions module.

This module defines the base types for exceptions and the platform-wide error codes as outlined in
https://cloud.google.com/apis/design/errors.
"""


INVALID_ARGUMENT = 'INVALID_ARGUMENT'
FAILED_PRECONDITION = 'FAILED_PRECONDITION'
OUT_OF_RANGE = 'OUT_OF_RANGE'
UNAUTHENTICATED = 'UNAUTHENTICATED'
PERMISSION_DENIED = 'PERMISSION_DENIED'
NOT_FOUND = 'NOT_FOUND'
CONFLICT = 'CONFLICT'
ABORTED = 'ABORTED'
ALREADY_EXISTS = 'ALREADY_EXISTS'
RESOURCE_EXHAUSTED = 'RESOURCE_EXHAUSTED'
CANCELLED = 'CANCELLED'
DATA_LOSS = 'DATA_LOSS'
UNKNOWN = 'UNKNOWN'
INTERNAL = 'INTERNAL'
UNAVAILABLE = 'UNAVAILABLE'
DEADLINE_EXCEEDED = 'DEADLINE_EXCEEDED'


class FirebaseError(Exception):
"""Base class for all errors raised by the Admin SDK."""

def __init__(self, code, message, cause=None, http_response=None):
Exception.__init__(self, message)
self._code = code
self._cause = cause
self._http_response = http_response

@property
def code(self):
return self._code

@property
def cause(self):
return self._cause

@property
def http_response(self):
return self._http_response


class InvalidArgumentError(FirebaseError):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want doc strings on all these types? We could reuse the comments from the status proto file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Took documentation from the GCP docs.

"""Client specified an invalid argument."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, INVALID_ARGUMENT, message, cause, http_response)


class FailedPreconditionError(FirebaseError):
"""Request can not be executed in the current system state, such as deleting a non-empty
directory."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, FAILED_PRECONDITION, message, cause, http_response)


class OutOfRangeError(FirebaseError):
"""Client specified an invalid range."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, OUT_OF_RANGE, message, cause, http_response)


class UnauthenticatedError(FirebaseError):
"""Request not authenticated due to missing, invalid, or expired OAuth token."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, UNAUTHENTICATED, message, cause, http_response)


class PermissionDeniedError(FirebaseError):
"""Client does not have sufficient permission.

This can happen because the OAuth token does not have the right scopes, the client doesn't
have permission, or the API has not been enabled for the client project.
"""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, PERMISSION_DENIED, message, cause, http_response)


class NotFoundError(FirebaseError):
"""A specified resource is not found, or the request is rejected by undisclosed reasons, such
as whitelisting."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, NOT_FOUND, message, cause, http_response)


class ConflictError(FirebaseError):
"""Concurrency conflict, such as read-modify-write conflict."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, CONFLICT, message, cause, http_response)


class AbortedError(FirebaseError):
"""Concurrency conflict, such as read-modify-write conflict."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, ABORTED, message, cause, http_response)


class AlreadyExistsError(FirebaseError):
"""The resource that a client tried to create already exists."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, ALREADY_EXISTS, message, cause, http_response)


class ResourceExhaustedError(FirebaseError):
"""Either out of resource quota or reaching rate limiting."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, RESOURCE_EXHAUSTED, message, cause, http_response)


class CancelledError(FirebaseError):
"""Request cancelled by the client."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, CANCELLED, message, cause, http_response)


class DataLossError(FirebaseError):
"""Unrecoverable data loss or data corruption."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, DATA_LOSS, message, cause, http_response)


class UnknownError(FirebaseError):
"""Unknown server error."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, UNKNOWN, message, cause, http_response)


class InternalError(FirebaseError):
"""Internal server error."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, INTERNAL, message, cause, http_response)


class UnavailableError(FirebaseError):
"""Service unavailable. Typically the server is down."""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, UNAVAILABLE, message, cause, http_response)


class DeadlineExceededError(FirebaseError):
"""Request deadline exceeded.

This will happen only if the caller sets a deadline that is shorter than the method's
default deadline (i.e. requested deadline is not enough for the server to process the
request) and the request did not finish within the deadline.
"""

def __init__(self, message, cause=None, http_response=None):
FirebaseError.__init__(self, DEADLINE_EXCEEDED, message, cause, http_response)
15 changes: 4 additions & 11 deletions firebase_admin/instance_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,6 @@ def delete_instance_id(instance_id, app=None):
_get_iid_service(app).delete_instance_id(instance_id)


class ApiCallError(Exception):
"""Represents an Exception encountered while invoking the Firebase instance ID service."""

def __init__(self, message, error):
Exception.__init__(self, message)
self.detail = error


class _InstanceIdService(object):
"""Provides methods for interacting with the remote instance ID service."""

Expand Down Expand Up @@ -94,14 +86,15 @@ def delete_instance_id(self, instance_id):
try:
self._client.request('delete', path)
except requests.exceptions.RequestException as error:
raise ApiCallError(self._extract_message(instance_id, error), error)
msg = self._extract_message(instance_id, error)
raise _utils.handle_requests_error(error, msg)

def _extract_message(self, instance_id, error):
if error.response is None:
return str(error)
return None
status = error.response.status_code
msg = self.error_codes.get(status)
if msg:
return 'Instance ID "{0}": {1}'.format(instance_id, msg)
else:
return str(error)
return 'Instance ID "{0}": {1}'.format(instance_id, error)
3 changes: 2 additions & 1 deletion integration/test_instance_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@

import pytest

from firebase_admin import exceptions
from firebase_admin import instance_id

def test_delete_non_existing():
with pytest.raises(instance_id.ApiCallError) as excinfo:
with pytest.raises(exceptions.NotFoundError) as excinfo:
# legal instance IDs are /[cdef][A-Za-z0-9_-]{9}[AEIMQUYcgkosw048]/
instance_id.delete_instance_id('fictive-ID0')
assert str(excinfo.value) == 'Instance ID "fictive-ID0": Failed to find the instance ID.'
96 changes: 96 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import requests
from requests import models

from firebase_admin import exceptions
from firebase_admin import _utils


def test_timeout_error():
error = requests.exceptions.Timeout('Test error')
firebase_error = _utils.handle_requests_error(error)
assert isinstance(firebase_error, exceptions.DeadlineExceededError)
assert str(firebase_error) == 'Timed out while making an API call: Test error'
assert firebase_error.cause is error
assert firebase_error.http_response is None

def test_connection_error():
error = requests.exceptions.ConnectionError('Test error')
firebase_error = _utils.handle_requests_error(error)
assert isinstance(firebase_error, exceptions.UnavailableError)
assert str(firebase_error) == 'Failed to establish a connection: Test error'
assert firebase_error.cause is error
assert firebase_error.http_response is None

def test_unknown_transport_error():
error = requests.exceptions.RequestException('Test error')
firebase_error = _utils.handle_requests_error(error)
assert isinstance(firebase_error, exceptions.UnknownError)
assert str(firebase_error) == 'Unknown error while making a remote service call: Test error'
assert firebase_error.cause is error
assert firebase_error.http_response is None

def test_http_response():
resp = models.Response()
resp.status_code = 500
error = requests.exceptions.RequestException('Test error', response=resp)
firebase_error = _utils.handle_requests_error(error)
assert isinstance(firebase_error, exceptions.InternalError)
assert str(firebase_error) == 'Test error'
assert firebase_error.cause is error
assert firebase_error.http_response is resp

def test_http_response_with_unknown_status():
resp = models.Response()
resp.status_code = 501
error = requests.exceptions.RequestException('Test error', response=resp)
firebase_error = _utils.handle_requests_error(error)
assert isinstance(firebase_error, exceptions.UnknownError)
assert str(firebase_error) == 'Test error'
assert firebase_error.cause is error
assert firebase_error.http_response is resp

def test_http_response_with_message():
resp = models.Response()
resp.status_code = 500
error = requests.exceptions.RequestException('Test error', response=resp)
firebase_error = _utils.handle_requests_error(error, message='Explicit error message')
assert isinstance(firebase_error, exceptions.InternalError)
assert str(firebase_error) == 'Explicit error message'
assert firebase_error.cause is error
assert firebase_error.http_response is resp

def test_http_response_with_status():
resp = models.Response()
resp.status_code = 500
error = requests.exceptions.RequestException('Test error', response=resp)
firebase_error = _utils.handle_requests_error(error, status=503)
assert isinstance(firebase_error, exceptions.UnavailableError)
assert str(firebase_error) == 'Test error'
assert firebase_error.cause is error
assert firebase_error.http_response is resp

def test_http_response_with_message_and_status():
resp = models.Response()
resp.status_code = 500
error = requests.exceptions.RequestException('Test error', response=resp)
firebase_error = _utils.handle_requests_error(
error, message='Explicit error message', status=503)
assert isinstance(firebase_error, exceptions.UnavailableError)
assert str(firebase_error) == 'Explicit error message'
assert firebase_error.cause is error
assert firebase_error.http_response is resp
Loading