Skip to content

Commit 4d37480

Browse files
author
Michael Brewer
committed
refactor: add status to the response
1 parent 88726a4 commit 4d37480

File tree

2 files changed

+65
-76
lines changed

2 files changed

+65
-76
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

+20-44
Original file line numberDiff line numberDiff line change
@@ -18,72 +18,44 @@
1818
class ServiceError(Exception):
1919
"""Service Error"""
2020

21-
def __init__(self, status_code: int, message: str):
21+
def __init__(self, status_code: int, msg: str):
2222
"""
2323
Parameters
2424
----------
25-
code: int
25+
status_code: int
2626
Http status code
27-
message: str
27+
msg: str
2828
Error message
2929
"""
3030
self.status_code = status_code
31-
self.message = message
32-
33-
def __str__(self) -> str:
34-
"""To string of the message only"""
35-
return self.message
31+
self.msg = msg
3632

3733

3834
class BadRequestError(ServiceError):
3935
"""Bad Request Error"""
4036

41-
def __init__(self, message: str):
42-
"""
43-
Parameters
44-
----------
45-
message: str
46-
Error message
47-
"""
48-
super().__init__(400, message)
37+
def __init__(self, msg: str):
38+
super().__init__(400, msg)
4939

5040

5141
class UnauthorizedError(ServiceError):
5242
"""Unauthorized Error"""
5343

54-
def __init__(self, message: str):
55-
"""
56-
Parameters
57-
----------
58-
message: str
59-
Error message
60-
"""
61-
super().__init__(401, message)
44+
def __init__(self, msg: str):
45+
super().__init__(401, msg)
6246

6347

6448
class NotFoundError(ServiceError):
6549
"""Not Found Error"""
6650

67-
def __init__(self, message: str = "Not found"):
68-
"""
69-
Parameters
70-
----------
71-
message: str
72-
Error message
73-
"""
74-
super().__init__(404, message)
51+
def __init__(self, msg: str = "Not found"):
52+
super().__init__(404, msg)
7553

7654

7755
class InternalServerError(ServiceError):
78-
"""Internal Serve Error"""
56+
"""Internal Server Error"""
7957

8058
def __init__(self, message: str):
81-
"""
82-
Parameters
83-
----------
84-
message: str
85-
Error message
86-
"""
8759
super().__init__(500, message)
8860

8961

@@ -542,7 +514,7 @@ def _not_found(self, method: str) -> ResponseBuilder:
542514
status_code=404,
543515
content_type=APPLICATION_JSON,
544516
headers=headers,
545-
body=json.dumps({"message": "Not found"}),
517+
body=self._json_dump({"code": 404, "message": "Not found"}),
546518
)
547519
)
548520

@@ -555,13 +527,12 @@ def _call_route(self, route: Route, args: Dict[str, str]) -> ResponseBuilder:
555527
Response(
556528
status_code=e.status_code,
557529
content_type=APPLICATION_JSON,
558-
body=json.dumps({"message": str(e)}),
530+
body=self._json_dump({"code": e.status_code, "message": e.msg}),
559531
),
560532
route,
561533
)
562534

563-
@staticmethod
564-
def _to_response(result: Union[Dict, Response]) -> Response:
535+
def _to_response(self, result: Union[Dict, Response]) -> Response:
565536
"""Convert the route's result to a Response
566537
567538
2 main result types are supported:
@@ -577,5 +548,10 @@ def _to_response(result: Union[Dict, Response]) -> Response:
577548
return Response(
578549
status_code=200,
579550
content_type=APPLICATION_JSON,
580-
body=json.dumps(result, separators=(",", ":"), cls=Encoder),
551+
body=self._json_dump(result),
581552
)
553+
554+
@staticmethod
555+
def _json_dump(obj: Any) -> str:
556+
"""Does a concise json serialization"""
557+
return json.dumps(obj, separators=(",", ":"), cls=Encoder)

tests/functional/event_handler/test_api_gateway.py

+45-32
Original file line numberDiff line numberDiff line change
@@ -498,72 +498,85 @@ def custom_method():
498498
assert headers["Access-Control-Allow-Methods"] == "CUSTOM"
499499

500500

501-
def test_service_error_response():
502-
# GIVEN a service error response
501+
def test_service_error_responses():
502+
# SCENARIO handling different kind of service errors being raised
503503
app = ApiGatewayResolver(cors=CORSConfig())
504504

505-
@app.route(method="GET", rule="/bad-request-error", cors=False)
505+
def json_dump(obj):
506+
return json.dumps(obj, separators=(",", ":"))
507+
508+
# GIVEN an BadRequestError
509+
@app.get(rule="/bad-request-error", cors=False)
506510
def bad_request_error():
507511
raise BadRequestError("Missing required parameter")
508512

509-
@app.route(method="GET", rule="/unauthorized-error", cors=False)
510-
def unauthorized_error():
511-
raise UnauthorizedError("Unauthorized")
512-
513-
@app.route(method="GET", rule="/service-error", cors=True)
514-
def service_error():
515-
raise ServiceError(403, "Unauthorized")
516-
517-
@app.route(method="GET", rule="/not-found-error", cors=False)
518-
def not_found_error():
519-
raise NotFoundError
520-
521-
@app.route(method="GET", rule="/internal-server-error", cors=False)
522-
def internal_server_error():
523-
raise InternalServerError("Internal server error")
524-
525513
# WHEN calling the handler
526514
# AND path is /bad-request-error
527515
result = app({"path": "/bad-request-error", "httpMethod": "GET"}, None)
528516
# THEN return the bad request error response
529517
# AND status code equals 400
530518
assert result["statusCode"] == 400
531-
assert result["body"] == json.dumps({"message": "Missing required parameter"})
532519
assert result["headers"]["Content-Type"] == APPLICATION_JSON
520+
expected = {"code": 400, "message": "Missing required parameter"}
521+
assert result["body"] == json_dump(expected)
522+
523+
# GIVEN an UnauthorizedError
524+
@app.get(rule="/unauthorized-error", cors=False)
525+
def unauthorized_error():
526+
raise UnauthorizedError("Unauthorized")
533527

534528
# WHEN calling the handler
535529
# AND path is /unauthorized-error
536530
result = app({"path": "/unauthorized-error", "httpMethod": "GET"}, None)
537531
# THEN return the unauthorized error response
538532
# AND status code equals 401
539533
assert result["statusCode"] == 401
540-
assert result["body"] == json.dumps({"message": "Unauthorized"})
541534
assert result["headers"]["Content-Type"] == APPLICATION_JSON
535+
expected = {"code": 401, "message": "Unauthorized"}
536+
assert result["body"] == json_dump(expected)
542537

543-
# WHEN calling the handler
544-
# AND path is /service-error
545-
result = app({"path": "/service-error", "httpMethod": "GET"}, None)
546-
# THEN return the service error response
547-
# AND status code equals 403
548-
assert result["statusCode"] == 403
549-
assert result["body"] == json.dumps({"message": "Unauthorized"})
550-
assert result["headers"]["Content-Type"] == APPLICATION_JSON
551-
assert "Access-Control-Allow-Origin" in result["headers"]
538+
# GIVEN an NotFoundError
539+
@app.get(rule="/not-found-error", cors=False)
540+
def not_found_error():
541+
raise NotFoundError
552542

553543
# WHEN calling the handler
554544
# AND path is /not-found-error
555545
result = app({"path": "/not-found-error", "httpMethod": "GET"}, None)
556546
# THEN return the not found error response
557547
# AND status code equals 404
558548
assert result["statusCode"] == 404
559-
assert result["body"] == json.dumps({"message": "Not found"})
560549
assert result["headers"]["Content-Type"] == APPLICATION_JSON
550+
expected = {"code": 404, "message": "Not found"}
551+
assert result["body"] == json_dump(expected)
552+
553+
# GIVEN an InternalServerError
554+
@app.get(rule="/internal-server-error", cors=False)
555+
def internal_server_error():
556+
raise InternalServerError("Internal server error")
561557

562558
# WHEN calling the handler
563559
# AND path is /internal-server-error
564560
result = app({"path": "/internal-server-error", "httpMethod": "GET"}, None)
565561
# THEN return the internal server error response
566562
# AND status code equals 500
567563
assert result["statusCode"] == 500
568-
assert result["body"] == json.dumps({"message": "Internal server error"})
569564
assert result["headers"]["Content-Type"] == APPLICATION_JSON
565+
expected = {"code": 500, "message": "Internal server error"}
566+
assert result["body"] == json_dump(expected)
567+
568+
# GIVEN an ServiceError with a custom status code
569+
@app.get(rule="/service-error", cors=True)
570+
def service_error():
571+
raise ServiceError(502, "Something went wrong!")
572+
573+
# WHEN calling the handler
574+
# AND path is /service-error
575+
result = app({"path": "/service-error", "httpMethod": "GET"}, None)
576+
# THEN return the service error response
577+
# AND status code equals 502
578+
assert result["statusCode"] == 502
579+
assert result["headers"]["Content-Type"] == APPLICATION_JSON
580+
assert "Access-Control-Allow-Origin" in result["headers"]
581+
expected = {"code": 502, "message": "Something went wrong!"}
582+
assert result["body"] == json_dump(expected)

0 commit comments

Comments
 (0)