Skip to content

Commit fe7c512

Browse files
authored
docs(api-gateway): document new HTTP service error exceptions (#546)
1 parent 8ceb91c commit fe7c512

File tree

2 files changed

+87
-2
lines changed

2 files changed

+87
-2
lines changed

Diff for: docs/core/event_handler/api_gateway.md

+86-2
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ You can access the raw payload via `body` property, or if it's a JSON string you
357357

358358
#### Headers
359359

360-
Similarly to [Query strings](#query-strings), you can access headers as dictionary via `app.current_event.headers`, or by name via `get_header_value`.
360+
Similarly to [Query strings](#query-strings-and-payload), you can access headers as dictionary via `app.current_event.headers`, or by name via `get_header_value`.
361361

362362
=== "app.py"
363363

@@ -377,6 +377,66 @@ Similarly to [Query strings](#query-strings), you can access headers as dictiona
377377
return app.resolve(event, context)
378378
```
379379

380+
### Raising HTTP errors
381+
382+
You can easily raise any HTTP Error back to the client using `ServiceError` exception.
383+
384+
!!! info "If you need to send custom headers, use [Response](#fine-grained-responses) class instead."
385+
386+
Additionally, we provide pre-defined errors for the most popular ones such as HTTP 400, 401, 404, 500.
387+
388+
389+
=== "app.py"
390+
391+
```python hl_lines="4-10 20 25 30 35 39"
392+
from aws_lambda_powertools import Logger, Tracer
393+
from aws_lambda_powertools.logging import correlation_paths
394+
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver
395+
from aws_lambda_powertools.event_handler.exceptions import (
396+
BadRequestError,
397+
InternalServerError,
398+
NotFoundError,
399+
ServiceError,
400+
UnauthorizedError,
401+
)
402+
403+
tracer = Tracer()
404+
logger = Logger()
405+
406+
app = ApiGatewayResolver()
407+
408+
@app.get(rule="/bad-request-error")
409+
def bad_request_error():
410+
# HTTP 400
411+
raise BadRequestError("Missing required parameter")
412+
413+
@app.get(rule="/unauthorized-error")
414+
def unauthorized_error():
415+
# HTTP 401
416+
raise UnauthorizedError("Unauthorized")
417+
418+
@app.get(rule="/not-found-error")
419+
def not_found_error():
420+
# HTTP 404
421+
raise NotFoundError
422+
423+
@app.get(rule="/internal-server-error")
424+
def internal_server_error():
425+
# HTTP 500
426+
raise InternalServerError("Internal server error")
427+
428+
@app.get(rule="/service-error", cors=True)
429+
def service_error():
430+
raise ServiceError(502, "Something went wrong!")
431+
# alternatively
432+
# from http import HTTPStatus
433+
# raise ServiceError(HTTPStatus.BAD_GATEWAY.value, "Something went wrong)
434+
435+
def handler(event, context):
436+
return app.resolve(event, context)
437+
```
438+
439+
380440
## Advanced
381441

382442
### CORS
@@ -401,7 +461,7 @@ This will ensure that CORS headers are always returned as part of the response w
401461
@app.get("/hello/<name>")
402462
@tracer.capture_method
403463
def get_hello_you(name):
404-
return {"message": f"hello {name}}"}
464+
return {"message": f"hello {name}"}
405465

406466
@app.get("/hello", cors=False) # optionally exclude CORS from response, if needed
407467
@tracer.capture_method
@@ -647,6 +707,30 @@ Like `compress` feature, the client must send the `Accept` header with the corre
647707
}
648708
```
649709

710+
### Debug mode
711+
712+
You can enable debug mode via `debug` param, or via `POWERTOOLS_EVENT_HANDLER_DEBUG` [environment variable](../../index.md#environment-variables).
713+
714+
This will enable full tracebacks errors in the response, print request and responses, and set CORS in development mode.
715+
716+
!!! warning "This might reveal sensitive information in your logs and relax CORS restrictions, use it sparingly."
717+
718+
=== "debug.py"
719+
720+
```python hl_lines="3"
721+
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver
722+
723+
app = ApiGatewayResolver(debug=True)
724+
725+
@app.get("/hello")
726+
def get_hello_universe():
727+
return {"message": "hello universe"}
728+
729+
def lambda_handler(event, context):
730+
return app.resolve(event, context)
731+
```
732+
733+
650734
## Testing your code
651735

652736
You can test your routes by passing a proxy event request where `path` and `httpMethod`.

Diff for: docs/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ aws serverlessrepo list-application-versions \
229229
| **POWERTOOLS_LOGGER_LOG_EVENT** | Logs incoming event | [Logging](./core/logger) | `false` |
230230
| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logging](./core/logger) | `0` |
231231
| **POWERTOOLS_LOG_DEDUPLICATION_DISABLED** | Disables log deduplication filter protection to use Pytest Live Log feature | [Logging](./core/logger) | `false` |
232+
| **POWERTOOLS_EVENT_HANDLER_DEBUG** | Enables debugging mode for event handler | [Event Handler](./core/event_handler/api_gateway.md#debug-mode) | `false` |
232233
| **LOG_LEVEL** | Sets logging level | [Logging](./core/logger) | `INFO` |
233234

234235
## Debug mode

0 commit comments

Comments
 (0)