> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/charlietyn/rest-generic-class/llms.txt
> Use this file to discover all available pages before exploring further.

# DatabaseErrorParser

> Parse database errors into user-friendly messages with suggestions for PostgreSQL, MySQL, SQL Server, and MongoDB

## Overview

The `DatabaseErrorParser` class parses database errors from different engines (PostgreSQL, MySQL, SQL Server, MongoDB) and provides human-friendly error messages with actionable suggestions. It covers SELECT, INSERT, UPDATE, and DELETE errors including constraint violations, syntax errors, and data type issues.

## Class Reference

```php theme={null}
use Ronu\RestGenericClass\Core\Helpers\DatabaseErrorParser;
```

## Methods

### parse()

Parse database exception and return structured error information.

```php theme={null}
public static function parse(\Throwable $exception): array
```

<ParamField path="exception" type="\Throwable" required>
  The database exception to parse (PDOException, QueryException, etc.)
</ParamField>

<ResponseField name="return" type="array">
  Structured error information with the following keys:

  <Expandable title="Response Structure">
    <ResponseField name="title" type="string">
      User-friendly error title (e.g., "Column Not Found", "Duplicate Entry")
    </ResponseField>

    <ResponseField name="description" type="string">
      Detailed error description explaining what went wrong
    </ResponseField>

    <ResponseField name="hint" type="string|null">
      Database-provided hint (mainly from PostgreSQL HINT messages)
    </ResponseField>

    <ResponseField name="error_type" type="string">
      Error type identifier (e.g., "unique\_violation", "foreign\_key\_violation", "not\_null\_violation")
    </ResponseField>

    <ResponseField name="details" type="array">
      Extracted error details including:

      * `column`: Affected column name
      * `table`: Affected table name
      * `constraint`: Constraint name
      * `sqlstate`: SQL state code
      * `database_driver`: Database driver (pgsql, mysql, sqlsrv, mongodb)
    </ResponseField>

    <ResponseField name="suggestion" type="string|null">
      Actionable suggestion for fixing the error
    </ResponseField>

    <ResponseField name="operation" type="string|null">
      SQL operation type (SELECT, INSERT, UPDATE, DELETE)
    </ResponseField>
  </Expandable>
</ResponseField>

#### Example Usage

```php theme={null}
use Ronu\RestGenericClass\Core\Helpers\DatabaseErrorParser;

try {
    // Database operation that fails
    DB::table('users')->insert([
        'email' => 'duplicate@example.com'
    ]);
} catch (\Throwable $e) {
    $error = DatabaseErrorParser::parse($e);
    
    // Returns:
    // [
    //   'title' => 'Duplicate Entry',
    //   'description' => 'Cannot insert duplicate entry...',
    //   'hint' => null,
    //   'error_type' => 'duplicate_entry',
    //   'details' => [
    //     'duplicate_value' => 'duplicate@example.com',
    //     'index' => 'users_email_unique',
    //     'database_driver' => 'mysql'
    //   ],
    //   'suggestion' => 'Either use a different value or update...',
    //   'operation' => 'INSERT'
    // ]
}
```

***

### toExceptionError()

Convert parsed error to a DatabaseErrorParserException with JSON response format.

```php theme={null}
public static function toExceptionError(array $parsedError, int $statusCode = 400): \DatabaseErrorParserException
```

<ParamField path="parsedError" type="array" required>
  The parsed error array from `parse()` method
</ParamField>

<ParamField path="statusCode" type="int" default="400">
  HTTP status code for the exception
</ParamField>

<ResponseField name="throws" type="DatabaseErrorParserException">
  Exception with JSON-encoded error details in the message
</ResponseField>

#### Example Usage

```php theme={null}
try {
    DB::table('users')->insert(['email' => null]);
} catch (\Throwable $e) {
    $parsed = DatabaseErrorParser::parse($e);
    
    // Throw formatted exception
    DatabaseErrorParser::toExceptionError($parsed, 422);
    
    // Exception message contains JSON:
    // {
    //   "error": {
    //     "title": "NULL Value Not Allowed",
    //     "message": "Column 'email' cannot be NULL",
    //     "type": "not_null_violation",
    //     "operation": "INSERT",
    //     "suggestion": "Provide a value for 'email'...",
    //     "details": { ... } // Only in debug mode
    //   }
    // }
}
```

***

### toPlainText()

Format parsed error as plain text for logging.

```php theme={null}
public static function toPlainText(array $parsedError): string
```

<ParamField path="parsedError" type="array" required>
  The parsed error array from `parse()` method
</ParamField>

<ResponseField name="return" type="string">
  Formatted plain text error message
</ResponseField>

#### Example Usage

```php theme={null}
try {
    // Database operation
} catch (\Throwable $e) {
    $parsed = DatabaseErrorParser::parse($e);
    $text = DatabaseErrorParser::toPlainText($parsed);
    
    Log::error($text);
    // [INSERT] Duplicate Entry: Cannot insert duplicate entry 'test@example.com' for key 'users_email_unique'
    // Suggestion: Either use a different value or update the existing record instead of inserting a new one.
}
```

***

## Supported Error Types

### SELECT Errors

* **undefined\_column** / **unknown\_column** - Column does not exist
* **undefined\_table** / **unknown\_table** - Table does not exist
* **syntax\_error** - SQL syntax errors
* **duplicate\_column** - Column specified multiple times

### INSERT/UPDATE Errors

* **unique\_violation** / **duplicate\_entry** - Unique constraint violation
* **foreign\_key\_violation** - Foreign key constraint violation
* **not\_null\_violation** - NULL value in NOT NULL column
* **check\_violation** - Check constraint violation
* **invalid\_text\_representation** - Invalid data type format
* **data\_too\_long** - String data exceeds column length
* **numeric\_value\_out\_of\_range** - Number exceeds allowed range

### DELETE Errors

* **restrict\_violation** - Cannot delete referenced record
* **cannot\_delete\_parent** - Foreign key prevents deletion

### MongoDB Errors

* **duplicate\_key** - Duplicate key in unique index
* **validation\_failed** - Document validation failed
* **document\_too\_large** - Document exceeds 16MB limit
* **immutable\_field** - Cannot update immutable field
* **unknown\_operator** - Invalid MongoDB operator

***

## Error Type Mappings

### PostgreSQL (SQLSTATE Codes)

* `42703` - undefined\_column
* `42P01` - undefined\_table
* `42601` - syntax\_error
* `23505` - unique\_violation
* `23503` - foreign\_key\_violation
* `23502` - not\_null\_violation
* `23514` - check\_violation
* `22P02` - invalid\_text\_representation
* `22001` - string\_data\_right\_truncation
* `22003` - numeric\_value\_out\_of\_range
* `22012` - division\_by\_zero

### MySQL (SQLSTATE Codes)

* `42S22` - unknown\_column
* `42S02` - unknown\_table
* `42000` - syntax\_error
* `23000` - duplicate\_entry / foreign\_key\_constraint / column\_cannot\_be\_null
* `22001` - data\_too\_long
* `22007` - truncated\_incorrect\_value
* `22003` - out\_of\_range
* `22012` - division\_by\_zero

### SQL Server (SQLSTATE Codes)

* `42S22` - invalid\_column
* `42S02` - invalid\_object
* `42000` - syntax\_error
* `23000` - duplicate\_key / foreign\_key\_conflict / null\_constraint
* `22001` - string\_truncation
* `22000` - conversion\_failed
* `22003` - arithmetic\_overflow
* `22012` - divide\_by\_zero

***

## Complete Example

```php theme={null}
use Ronu\RestGenericClass\Core\Helpers\DatabaseErrorParser;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
    public function store(Request $request)
    {
        try {
            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
            ]);
            
            return response()->json($user, 201);
            
        } catch (\Throwable $e) {
            // Parse the error
            $parsed = DatabaseErrorParser::parse($e);
            
            // Log for debugging
            Log::error(DatabaseErrorParser::toPlainText($parsed));
            
            // Return user-friendly error
            return response()->json([
                'error' => [
                    'title' => $parsed['title'],
                    'message' => $parsed['description'],
                    'suggestion' => $parsed['suggestion'],
                ],
            ], 422);
        }
    }
}
```

***

## DatabaseErrorParserException

The exception thrown by `toExceptionError()` includes a helper method:

### getDatabaseErrorParsed()

Retrieve the parsed error data from the exception.

```php theme={null}
try {
    // Database operation
} catch (DatabaseErrorParserException $e) {
    $errorData = $e->getDatabaseErrorParsed();
    // Returns the decoded JSON array
}
```
