Skip to content
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

Convert any ChaliceViewError to a response #1886

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
12 changes: 9 additions & 3 deletions chalice/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ def __init__(self, connection_id):
class ChaliceViewError(ChaliceError):
STATUS_CODE = 500

def to_response(self):
return Response(
body={
'Code': self.__class__.__name__,
'Message': str(self)},
status_code=self.STATUS_CODE
)


class ChaliceUnhandledError(ChaliceError):
"""This error is not caught from a Chalice view function.
Expand Down Expand Up @@ -1760,9 +1768,7 @@ def _get_view_function_response(self, view_function, function_args):
except ChaliceViewError as e:
# Any chalice view error should propagate. These
# get mapped to various HTTP status codes in API Gateway.
response = Response(body={'Code': e.__class__.__name__,
'Message': str(e)},
status_code=e.STATUS_CODE)
response = e.to_response()
except Exception:
response = self._unhandled_exception_to_response()
return response
Expand Down
54 changes: 54 additions & 0 deletions docs/source/tutorials/basicrestapi.rst
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,60 @@ You can import these directly from the ``chalice`` package:

from chalice import UnauthorizedError

Custom errors
^^^^^^^^^^^^^

You can create a custom response by implementing your own exception class.
The response must be generated by the method ``to_response`` and be
inherited from ``ChaliceViewError``. A sample custom error should look
like this:

.. code-block:: python

from chalice import ChaliceViewError, Response

class GoneCity(ChaliceViewError):
city = None
STATUS_CODE = 410

def __init__(self, city):
super().__init__()
self.city = city

def to_response(self):
return Response(
body=dict(
error=self.__class__.__name__,
message=f"The city of {self.city} has been abandoned",
city=self.city,
),
status_code=self.STATUS_CODE,
)

@app.route('/cities/{city}')
def state_of_city(city):
try:
if city in ABANDONED_CITIES:
raise GoneCity(city)
return {'state': CITIES_TO_STATE[city]}
except KeyError:
raise BadRequestError("Unknown city '%s', valid choices are: %s" % (
city, ', '.join(CITIES_TO_STATE.keys())))


Save and deploy these changes::

$ chalice deploy
$ http https://endpoint/api/cities/petra
HTTP/1.1 410 Gone

{
"error": "Gone",
"message": "The city of Petra has been abandoned",
"city": "petra"
}



Additional Routing
------------------
Expand Down
66 changes: 66 additions & 0 deletions tests/unit/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from chalice.test import Client
from chalice.app import (
APIGateway,
ChaliceViewError,
Request,
Response,
handle_extra_types,
Expand Down Expand Up @@ -1042,6 +1043,71 @@ def notfound():
assert json_response_body(raw_response)['Code'] == 'NotFoundError'


def test_chalice_view_custom_error_in_non_debug_mode(sample_app, create_event):
class CustomError(ChaliceViewError):
message = None

def __init__(self, code, message):
super().__init__()
self.STATUS_CODE = code
self.message = message

def to_response(self):
return Response(
body=dict(
error=self.__class__.__name__,
custom_msg=str(self.message)
),
status_code=self.STATUS_CODE,
)

err_code = 503
err_msg = "Method not available"

@sample_app.route('/internalerr')
def internalerr():
raise CustomError(err_code, err_msg)

event = create_event('/internalerr', 'GET', {})
raw_response = sample_app(event, context=None)
assert raw_response['statusCode'] == err_code
assert json_response_body(raw_response)['error'] == 'CustomError'
assert json_response_body(raw_response)['custom_msg'] == err_msg


def test_chalice_view_custom_error_in_debug_mode(sample_app, create_event):
class CustomError(ChaliceViewError):
message = None

def __init__(self, code, message):
super().__init__()
self.STATUS_CODE = code
self.message = message

def to_response(self):
return Response(
body=dict(
error=self.__class__.__name__,
custom_msg=str(self.message)
),
status_code=self.STATUS_CODE,
)

err_code = 503
err_msg = "Method not available"

@sample_app.route('/internalerr')
def internalerr():
raise CustomError(err_code, err_msg)
sample_app.debug = True

event = create_event('/internalerr', 'GET', {})
raw_response = sample_app(event, context=None)
assert raw_response['statusCode'] == err_code
assert json_response_body(raw_response)['error'] == 'CustomError'
assert json_response_body(raw_response)['custom_msg'] == err_msg


def test_case_insensitive_mapping():
mapping = app.CaseInsensitiveMapping({'HEADER': 'Value'})

Expand Down