import logging import typing import json from marshmallow import ValidationError import werkzeug from werkzeug.exceptions import Forbidden def create_validation_error_response(ex:ValidationError, status_code:int=400)->typing.Tuple[str,int]: # generate an overview the errors #example: # {'lock_time': ['The provided value must be in the future. Current Time: 2024-09-02 08:23:32.600791, Value: 2024-09-01 08:20:41.853000']} errors = ex.messages # example: # "Valid Data": { # "id": 2894, # "eta_berth": "datetime.datetime(2024, 9, 2, 11, 11, 43)", # "eta_berth_fixed": false # } valid_data = ex.valid_data json_response = { "message":"ValidationError", "errors":errors, "valid_data":valid_data } # json.dumps with default=str automatically converts non-serializable values to strings. Hence, datetime objects (which are not) # natively serializable are properly serialized. serialized_response = json.dumps(json_response, default=str) return (serialized_response, status_code) def create_werkzeug_error_response(ex:Forbidden, status_code:int=403)->typing.Tuple[str,int]: # json.dumps with default=str automatically converts non-serializable values to strings. Hence, datetime objects (which are not) # natively serializable are properly serialized. serialized_response = json.dumps({"message":ex.description}, default=str) return serialized_response, status_code