> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.sophra.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Cortex Error Handler Middleware

> A robust error handling middleware for the Sophra System's Cortex module

The Cortex Error Handler Middleware is a critical component of the Sophra System's error management infrastructure. This middleware serves as a centralized error processing unit, designed to intercept, log, and format errors that occur within the Cortex module of the Sophra platform. By leveraging Next.js 14's server-side capabilities and TypeScript's strong typing, this handler ensures consistent error reporting across the system.

Integrated deeply with Sophra's core logging and response mechanisms, the error handler plays a pivotal role in maintaining system stability and providing valuable debugging information. It utilizes a custom logger implementation, which is tailored to the specific needs of the Cortex module, ensuring that all errors are contextually relevant and traceable.

One of the key architectural decisions in this component is the use of Next.js's `NextResponse` for generating standardized error responses. This choice aligns with Sophra's microservices-oriented architecture, allowing for consistent error handling across different services while maintaining the flexibility to customize responses as needed.

Performance-wise, the error handler is designed to be lightweight and non-blocking. It employs a streamlined approach to error processing, avoiding complex operations that could introduce latency. The handler's efficiency is crucial, as it may be invoked frequently in high-traffic scenarios, particularly during peak load times or when the system is under stress.

A unique feature of this error handler is its ability to differentiate between standard `Error` objects and unknown error types. This capability ensures that even unexpected error scenarios are handled gracefully, providing a robust safety net for the entire Cortex module. The handler's output is structured to facilitate easy integration with monitoring tools and analytics pipelines, supporting Sophra's comprehensive monitoring infrastructure.

## Exported Components

<CodeGroup>
  ```typescript theme={null}
  export function handleError(error: unknown, context: string): NextResponse
  ```
</CodeGroup>

The `handleError` function is the primary export of this middleware. It takes two parameters:

* `error: unknown`: The error object to be processed. This can be of any type, allowing for maximum flexibility in error handling.
* `context: string`: A string describing the context in which the error occurred, providing additional information for debugging.

The function returns a `NextResponse` object, which is used by Next.js to send an HTTP response.

## Implementation Examples

<CodeGroup>
  ```typescript theme={null}
  import { handleError } from "@/lib/cortex/middleware/error-handler";

  async function searchHandler(req: Request) {
    try {
      // Perform search operation
    } catch (error) {
      return handleError(error, "Search operation");
    }
  }
  ```
</CodeGroup>

In this example, the `handleError` function is used within a search handler to process any errors that occur during the search operation. The context "Search operation" is provided to give more specific information about where the error occurred.

## Sophra Integration Details

The error handler integrates with Sophra's logging system through the imported `logger` module. It sets a specific service identifier for the logger:

<CodeGroup>
  ```typescript theme={null}
  const typedLogger = logger as unknown as Logger;
  typedLogger.service = "cortex-error-handler";
  ```
</CodeGroup>

This integration ensures that all errors logged through this handler are properly tagged and can be easily filtered in Sophra's centralized logging system.

## Error Handling

The error handler provides comprehensive error processing:

<AccordionGroup>
  <Accordion title="Standard Errors">
    For errors that are instances of the standard `Error` class, the handler extracts the error message and name, providing detailed information in the response.

    ```typescript theme={null}
    if (error instanceof Error) {
      return NextResponse.json(
        {
          success: false,
          error: `${context} failed`,
          details: error.message,
          type: error.name,
        },
        { status: 500 }
      );
    }
    ```
  </Accordion>

  <Accordion title="Unknown Errors">
    For errors that are not standard `Error` instances, the handler provides a generic error message to ensure that some information is always returned.

    ```typescript theme={null}
    return NextResponse.json(
      {
        success: false,
        error: `${context} failed`,
        details: "Unknown error occurred",
      },
      { status: 500 }
    );
    ```
  </Accordion>
</AccordionGroup>

## Data Flow

The error handling process follows this sequence:

```mermaid theme={null}
sequenceDiagram
    participant A as Application Code
    participant H as handleError Function
    participant L as Logger
    participant R as NextResponse

    A->>H: Call with error and context
    H->>L: Log error with context
    H->>H: Determine error type
    alt is Error instance
        H->>R: Create response with error details
    else is unknown error
        H->>R: Create response with generic message
    end
    H-->>A: Return NextResponse
```

## Performance Considerations

The error handler is designed for minimal overhead:

* It performs a single type check to determine the error structure.
* Logging is done asynchronously to prevent blocking.
* The response generation is streamlined, with no complex computations.

## Security Implementation

While primarily focused on error handling, this component contributes to security by:

* Avoiding exposure of sensitive error details in production environments.
* Providing consistent error responses to prevent information leakage.
* Integrating with Sophra's logging system for audit trails.

## Configuration

The error handler uses the following configuration:

<CodeGroup>
  ```typescript theme={null}
  // Environment-specific logger configuration
  import logger from "@/lib/shared/logger";

  // TypeScript type definitions
  import type { Logger } from "@/lib/shared/types";
  ```
</CodeGroup>

<Note>
  The specific logger configuration and type definitions are managed in separate files, allowing for environment-specific customization without changing the error handler code.
</Note>
