From 10e5a94b81d9b494d3b338b93da5dbffc1e5be93 Mon Sep 17 00:00:00 2001 From: Alejandro Cabeza Romero Date: Sat, 13 Nov 2021 17:55:14 +0100 Subject: [PATCH] Add API error handling usage example. --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/README.md b/README.md index 967f375..b305151 100644 --- a/README.md +++ b/README.md @@ -42,3 +42,38 @@ There's a priority hierarchy to know what handler to use: # Installation `pip install flexceptions` + +# Usage Examples + +### API Error Handling +One use case I like abstracting with this library is an exception hierarchy system that is castable to an HTTP Response object. Then, by decorating views with `handle_flexception`, every raised Flexception will have its `handle` method called, ensuring a proper object is sent back. + +It's also worth to mention that the `handle_flexception` decorator accepts a `handler` that is passed on to the `handle` method. +```python +from typing import Dict +from flexceptions import BaseFlexception, Handler, handle_flexception + + +class Request: + ... + +class Response: + ... + + +def _transform_to_http_response(exception: "MyApiException") -> Response: + return Response(status_code=exception.status_code, json=exception.json) + + +class MyApiException(BaseFlexception): + DEFAULT_HANDLER: Handler = _transform_to_http_response + + def __init__(self, status_code: int = 400, json: Dict = None) -> None: + self.status_code: int = status_code + self.json: Dict = json or dict() + + +@handle_flexception +def view(request: Request) -> Response: + ... +```