# Error Handler

ErrorHandler is a built-in FhyTS component responsible for centralized error handling. It logs error details using a Logger and responds to clients in a consistent JSON format.

## Purpose

* Provides global error handling for all HTTP requests.
* Prevents crashes due to unhandled exceptions.
* Ensures error messages are delivered to clients in a safe and structured manner.

## API Reference

### ErrorHandler.handle(err, req, res)

Handles error objects thrown during the HTTP request process.

| Parameters | Type | Description |
| --------- | ---------- | ---------------------------------------------- |
| `err` | `any` | The error object to be captured. |
| `req` | `Request` | The request object when the error occurred. |
| `res` | `Response` | The response object for sending error responses. |

## Response Format

```json
{
  "error": "Error message that occurs"
}
```

**By default**:

* Status code: **500 Internal Server Error**
* Message: **"Internal Server Error"**

However, if **err** has a **statusCode** and **message**, those values ​​will be used.

## Usage Example

#### In a Manual HTTP Server

```javascript
import { ErrorHandler } from 'fhyts';

try {
  // ... main process
} catch (err) {
  ErrorHandler.handle(err, req, res);
}
```

#### In Routing/Controller

```javascript
export const exampleHandler = async (req: Request, res: Response) => {
  try {
    throw new Error('Something went wrong');
  } catch (err) {
    ErrorHandler.handle(err, req, res);
  }
};
```

## Logger Integration

All errors are automatically logged via Logger.error() with information about the method and URL that caused the error.

Example output:

```bash
[ERROR] Error on GET /users Error: Something went wrong
```

## Best Practices

* Use an ErrorHandler as a fallback in the upper layers of your application.
* Add a statusCode property to your custom errors if you want to control the HTTP status:

```javascript
const err = new Error('User not found');
err.statusCode = 404;
throw err;
```

* Avoid sending internal application details to production clients (control via env).