testnexus-backend / utils /exceptions.py
Divyaraj1617's picture
Added server files
4db2610
Raw History Blame Contribute Delete
7.59 kB
from fastapi import HTTPException, status
from typing import Optional, Any
class BaseAPIException(HTTPException):
"""
Base exception class for custom API errors
Similar to creating custom error classes in Express
"""
def __init__(
self,
status_code: int,
message: str,
error: Optional[str] = None,
details: Optional[Any] = None
):
self.message = message
self.error = error or message
self.details = details
super().__init__(status_code=status_code, detail=message)
class BadRequestException(BaseAPIException):
"""400 Bad Request - Invalid input or validation error"""
def __init__(self, message: str = "Bad request", error: Optional[str] = None, details: Optional[Any] = None):
super().__init__(
status_code=status.HTTP_400_BAD_REQUEST,
message=message,
error=error or "Bad Request",
details=details
)
class UnauthorizedException(BaseAPIException):
"""401 Unauthorized - Authentication required"""
def __init__(self, message: str = "Unauthorized", error: Optional[str] = None, details: Optional[Any] = None):
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED,
message=message,
error=error or "Unauthorized",
details=details
)
class ForbiddenException(BaseAPIException):
"""403 Forbidden - Insufficient permissions"""
def __init__(self, message: str = "Forbidden", error: Optional[str] = None, details: Optional[Any] = None):
super().__init__(
status_code=status.HTTP_403_FORBIDDEN,
message=message,
error=error or "Forbidden",
details=details
)
class NotFoundException(BaseAPIException):
"""404 Not Found - Resource not found"""
def __init__(self, message: str = "Resource not found", error: Optional[str] = None, details: Optional[Any] = None):
super().__init__(
status_code=status.HTTP_404_NOT_FOUND,
message=message,
error=error or "Not Found",
details=details
)
class ConflictException(BaseAPIException):
"""409 Conflict - Resource conflict"""
def __init__(self, message: str = "Resource conflict", error: Optional[str] = None, details: Optional[Any] = None):
super().__init__(
status_code=status.HTTP_409_CONFLICT,
message=message,
error=error or "Conflict",
details=details
)
class InternalServerException(BaseAPIException):
"""500 Internal Server Error - Server error"""
def __init__(self, message: str = "Internal server error", error: Optional[str] = None, details: Optional[Any] = None):
super().__init__(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
message=message,
error=error or "Internal Server Error",
details=details
)
# =============================================================================
# MCP (Model Context Protocol) Exceptions
# =============================================================================
class MCPError(Exception):
"""
Base exception for MCP-related errors.
All MCP-specific exceptions inherit from this class, allowing for
easy catching of any MCP-related error.
"""
pass
class MCPSessionError(MCPError):
"""
Session terminated or connection lost.
Raised when the MCP session is unexpectedly closed or the connection
to the browser/MCP server is lost. This is typically recoverable
by reconnecting.
Attributes:
original_error: The underlying exception that caused this error
recoverable: Whether the error is potentially recoverable
"""
def __init__(
self,
message: str = "MCP session error",
original_error: Optional[Exception] = None,
recoverable: bool = True
):
super().__init__(message)
self.original_error = original_error
self.recoverable = recoverable
class MCPStaleRefError(MCPError):
"""
Element reference is stale (DOM changed).
Raised when an element reference (e.g., "e42") from a snapshot is no
longer valid because the page DOM has changed. The solution is typically
to take a new snapshot and find the element again.
Attributes:
ref: The stale reference that was used
tool_name: The tool that encountered the stale reference
"""
def __init__(self, ref: str, tool_name: str):
message = f"Stale element reference '{ref}' in tool '{tool_name}'"
super().__init__(message)
self.ref = ref
self.tool_name = tool_name
class MCPTimeoutError(MCPError):
"""
Tool execution timed out.
Raised when an MCP tool takes longer than its configured timeout.
This could indicate a slow page, network issues, or a stuck operation.
Attributes:
tool_name: The tool that timed out
timeout: The timeout value in seconds
"""
def __init__(self, tool_name: str, timeout: int):
message = f"Tool '{tool_name}' timed out after {timeout} seconds"
super().__init__(message)
self.tool_name = tool_name
self.timeout = timeout
class MCPRepeatedCallError(MCPError):
"""
Same tool+input called too many times (infinite loop prevention).
Raised when the agent attempts to call the same tool with the same
arguments multiple times in succession, indicating a potential
infinite loop or stuck state.
Attributes:
tool_name: The tool that was called repeatedly
call_count: Number of times the tool was called
max_calls: Maximum allowed calls before triggering this error
"""
def __init__(
self,
tool_name: str,
call_count: int,
max_calls: int = 4
):
message = f"Tool '{tool_name}' called {call_count} times with same input (max: {max_calls})"
super().__init__(message)
self.tool_name = tool_name
self.call_count = call_count
self.max_calls = max_calls
class MCPToolExecutionError(MCPError):
"""
Generic tool execution failure.
Raised when a tool execution fails for reasons other than timeout,
stale reference, or session errors.
Attributes:
tool_name: The tool that failed
tool_input: The input that was provided to the tool
original_error: The underlying exception
"""
def __init__(
self,
tool_name: str,
message: str,
tool_input: Optional[dict] = None,
original_error: Optional[Exception] = None
):
full_message = f"Tool '{tool_name}' failed: {message}"
super().__init__(full_message)
self.tool_name = tool_name
self.tool_input = tool_input
self.original_error = original_error
class MCPMaxStepsExceededError(MCPError):
"""
Maximum number of execution steps exceeded.
Raised when an automation task exceeds the maximum allowed number
of steps without completing. This is a safety mechanism to prevent
runaway executions.
Attributes:
max_steps: Maximum steps allowed
current_step: The step number when limit was reached
"""
def __init__(self, max_steps: int, current_step: int):
message = f"Maximum steps ({max_steps}) exceeded at step {current_step}"
super().__init__(message)
self.max_steps = max_steps
self.current_step = current_step