|
| 1 | +# API Errors in API class helpers |
| 2 | + |
| 3 | +Returning errors in the helper functions of your API endpoint can be annoying. |
| 4 | +To avoid that annoyance, just raise one of the [view exceptions](kirovy/exceptions/view_exceptions.py) |
| 5 | +or write your own that subclasses `KirovyValidationError`. |
| 6 | + |
| 7 | +**Example where you annoy yourself with bubbling returns:** |
| 8 | + |
| 9 | +```python |
| 10 | +class MyView(APIView): |
| 11 | + ... |
| 12 | + def helper(self, request: KirovyRequest) -> MyObject | KirovyResponse: |
| 13 | + object_id = request.data.get("id") |
| 14 | + if not object_id: |
| 15 | + return KirovyResponse( |
| 16 | + status=status.HTTP_400_BAD_REQUEST, |
| 17 | + data=ErrorResponseData( |
| 18 | + message="Must specify id", |
| 19 | + code=api_codes.FileUploadApiCodes.MISSING_FOREIGN_ID, |
| 20 | + additional={"expected_field": "id"} |
| 21 | + ) |
| 22 | + ) |
| 23 | + |
| 24 | + object = get_object_or_404(self.file_parent_class.objects, id=object_id) |
| 25 | + self.check_object_permissions(request, object) |
| 26 | + |
| 27 | + return object |
| 28 | + |
| 29 | + def post(self, request: KirovyRequest, format=None) -> KirovyResponse: |
| 30 | + object = self.helper(request) |
| 31 | + if isinstance(object, KirovyResponse): |
| 32 | + return object |
| 33 | + ... |
| 34 | +``` |
| 35 | + |
| 36 | +**Example where you just raise the exception:** |
| 37 | + |
| 38 | +```python |
| 39 | +class MyView(APIView): |
| 40 | + ... |
| 41 | + def helper(self, request: KirovyRequest) -> MyObject: |
| 42 | + object_id = request.data.get("id") |
| 43 | + if not object_id: |
| 44 | + raise KirovyValidationError( |
| 45 | + detail="Must specify id", |
| 46 | + code=api_codes.FileUploadApiCodes.MISSING_FOREIGN_ID, |
| 47 | + additional={"expected_field": "id"} |
| 48 | + ) |
| 49 | + |
| 50 | + object = get_object_or_404(self.file_parent_class.objects, id=object_id) |
| 51 | + self.check_object_permissions(request, object) |
| 52 | + |
| 53 | + return object |
| 54 | + |
| 55 | + def post(self, request: KirovyRequest, format=None) -> KirovyResponse: |
| 56 | + object = self.helper(request) |
| 57 | + ... |
| 58 | +``` |
0 commit comments