Coverage for nexios\auth\exceptions.py: 100%
13 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-21 20:31 +0100
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-21 20:31 +0100
1from nexios.exceptions import HTTPException
2from typing import Dict, Any, Optional
3from nexios.http import Request
4from nexios.http.response import NexiosResponse
6HeadersType = Dict[str, Any] # Alias for better readability
9class AuthException(HTTPException):
10 """
11 Base class for all authentication-related exceptions.
12 """
14 def __init__(
15 self, status_code: int, detail: str, headers: Optional[HeadersType] = None
16 ) -> None:
17 """
18 Initialize an authentication exception.
20 Args:
21 status_code (int): The HTTP status code.
22 detail (str): A description of the error.
23 headers (Optional[Dict[str, Any]]): Optional headers for the response.
24 """
25 super().__init__(status_code, detail, headers or {})
28class AuthenticationFailed(AuthException):
29 """
30 Raised when authentication fails.
31 """
33 def __init__(
34 self,
35 detail: str = "Authentication failed",
36 headers: Optional[HeadersType] = None,
37 ) -> None:
38 super().__init__(401, detail, headers)
41async def AuthErrorHandler(
42 req: Request, res: NexiosResponse, exc: HTTPException
43) -> Any:
44 """
45 Handle authentication exceptions and return a JSON response.
47 Args:
48 req (Request): The incoming HTTP request.
49 res (Response): The outgoing HTTP response.
50 exc (HTTPException): The raised HTTP exception.
52 Returns:
53 Response: JSON-formatted error response.
54 """
55 return res.json(exc.detail, status_code=exc.status_code, headers=exc.headers)