Coverage for src\zapy\api\exceptions.py: 26%

1 from pydantic import ValidationError

2

3 import traceback

4

5 from zapy.base.exceptions import ZapyException, HandledException

6

7 from fastapi import Request

8 from fastapi.responses import JSONResponse

9

10

11 def global_error_handler(request: Request, exception: Exception):

12 traceback.print_exc()

13 status_code = getattr(exception, "status_code", 500)

14 if isinstance(exception, HandledException):

15 status_code = 400

16 if isinstance(exception, ValidationError):

17 status_code = 400

18 exception.error_type = 'validation:json'

19 response = {

20 "error": str(exception),

21 "class": exception.__class__.__name__,

22 "error_type": getattr(exception, "error_type", "error:unhandled"),

23 }

24 if isinstance(exception, ZapyException):

25 response.update({

26 "class": "ZapyException",

27 "context": exception.context

28 })

29 return JSONResponse(response, status_code=status_code)