Documentation
Tout ce dont vous avez besoin pour intégrer Error Explorer
Guides complets, exemples de code et référence API pour démarrer rapidement avec Error Explorer.
Installation rapide
# Installation via Composer
composer require error-explorer/php-sdk
# Configuration en 30 secondes
ERROR_WEBHOOK_URL = https://error-explorer.com
ERROR_WEBHOOK_TOKEN = your-project-token
# Prêt à l'emploi !
Démarrage rapide
Commencez à utiliser Error Explorer en quelques minutes seulement. Suivez ce guide pour une configuration rapide et efficace.
Choisissez votre SDK
Sélectionnez votre framework ou langage pour obtenir les instructions adaptées.
Installez le SDK
Exécutez la commande d'installation pour votre framework.
Terminal
composer require error-explorer/symfony-sdk
Configurez Error Explorer
Ajoutez les variables d'environnement nécessaires à votre configuration.
.env
ERROR_WEBHOOK_URL=https://error-explorer.com
ERROR_WEBHOOK_TOKEN=your-project-token
PROJECT_NAME=my-project
ERROR_REPORTING_ENABLED=true
Testez l'intégration
Créez une erreur de test pour vérifier que tout fonctionne.
test.php
// Déclenchez une erreur de test
throw new Exception('Test error for Error Explorer');
Cas d'usage
Découvrez comment intégrer Error Explorer dans différents contextes et exploiter ses fonctionnalités avancées.
Capture d'erreurs dans les Controllers
Utilisez l'interface moderne avec gestion d'erreurs typée dans vos controllers Symfony.
ProductController.php
use ErrorExplorer\ErrorReporter\ErrorReporter;
use ErrorExplorer\ErrorReporter\Enum\LogLevel;
class ProductController extends AbstractController
{
public function show( int $id): Response
{
// Configuration contextuelle du reporter
$reporter = new ErrorReporter([
'dsn' => 'https://your-dsn@error-explorer.com/project',
'context' => [
'controller' => 'ProductController',
'action' => 'show',
'user_id' => $this->getUser()?->getId(),
'request_id' => uniqid()
]
]);
try {
// Log de démarrage pour traçabilité
$reporter->captureMessage(
'Accessing product details',
LogLevel::INFO,
['product_id' => $id]
);
// Logique métier avec gestion d'erreur
if ($id <= 0) {
throw new \InvalidArgumentException('Invalid product ID');
}
$product = $this->productRepository->find($id);
if (!$product) {
throw $this->createNotFoundException('Product not found');
}
return $this->render('product/show.html.twig', [
'product' => $product
]);
} catch (\Exception $exception) {
// Capture automatique avec contexte enrichi
$reporter->captureException($exception, [
'tags' => ['controller', 'product_access'],
'extra' => [
'attempted_product_id' => $id,
'user_role' => $this->getUser()?->getRoles(),
'request_method' => $this->request?->getMethod()
]
]);
// Re-lancer pour gestion globale
throw $exception;
}
}
}
Services et Injection de dépendances
Intégrez Error Explorer dans vos services Symfony avec une configuration DI native.
OrderProcessingService.php
use ErrorExplorer\ErrorReporter\ErrorReporter;
use ErrorExplorer\ErrorReporter\Enum\LogLevel;
use Psr\Log\LoggerInterface;
class OrderProcessingService
{
public function __construct(
private ErrorReporter $errorReporter,
private LoggerInterface $logger,
private PaymentGateway $paymentGateway
) {}
public function processOrder(Order $order): bool
{
// Breadcrumb pour tracer le processus
$this->errorReporter->addBreadcrumb([
'message' => 'Starting order processing',
'category' => 'order.processing',
'data' => [
'order_id' => $order->getId(),
'total_amount' => $order->getTotal(),
'customer_id' => $order->getCustomer()->getId()
]
]);
try {
// Validation de la commande
if (!$order->isValid()) {
throw new \InvalidArgumentException('Invalid order state');
}
// Traitement du paiement avec retry logic
$paymentResult = $this->processPayment($order);
if ($paymentResult->isSuccessful()) {
$this->logger->info('Order processed successfully', [
'order_id' => $order->getId()
]);
return true ;
}
return false ;
} catch (\Exception $exception) {
// Capture avec contexte service complet
$this->errorReporter->captureException($exception, [
'level' => LogLevel::ERROR,
'tags' => ['order', 'payment', 'critical'],
'fingerprint' => ['order.processing.error', $order->getId()],
'extra' => [
'order_data' => $order->toArray(),
'payment_gateway' => $this->paymentGateway->getName(),
'retry_count' => $this->getCurrentRetryCount()
]
]);
throw $exception;
}
}
}
Monitoring des Commands
Surveillez l'exécution de vos commandes Symfony avec des metrics détaillées et alertes automatiques.
ProcessOrdersCommand.php
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use ErrorExplorer\ErrorReporter\ErrorReporter;
#[AsCommand(
name: 'app:process-orders',
description: 'Process pending orders with monitoring'
)]
class ProcessOrdersCommand extends Command
{
public function __construct(
private ErrorReporter $errorReporter,
private OrderRepository $orderRepository
) {
parent ::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$startTime = microtime(true);
$processedCount = 0;
// Configuration du monitoring pour command
$this->errorReporter->configureScope([
'tags' => ['command', 'batch_processing'],
'extra' => [
'command_name' => 'app:process-orders',
'started_at' => date('Y-m-d H:i:s'),
'memory_limit' => ini_get('memory_limit')
]
]);
try {
$pendingOrders = $this->orderRepository->findPendingOrders();
$output->writeln(sprintf('Processing %d orders...', count($pendingOrders)));
foreach ($pendingOrders as $order) {
try {
$this->processOrder($order);
$processedCount++;
} catch (\Exception $e) {
// Capture mais continue le traitement
$this->errorReporter->captureException($e, [
'tags' => ['order_processing_error'],
'extra' => ['order_id' => $order->getId()]
]);
}
}
// Rapport de fin avec métriques
$executionTime = microtime(true) - $startTime;
$this->errorReporter->captureMessage('Command completed', 'info', [
'processed_orders' => $processedCount,
'execution_time_seconds' => round($executionTime, 2),
'memory_peak_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2)
]);
return Command::SUCCESS;
} catch (\Exception $exception) {
// Erreur critique de command
$this->errorReporter->captureException($exception, [
'level' => 'error',
'tags' => ['command_failure', 'critical'],
'extra' => [
'processed_before_failure' => $processedCount,
'execution_time' => microtime(true) - $startTime
]
]);
return Command::FAILURE;
}
}
}
Surveillance des Queue Jobs
Surveillez vos jobs Laravel avec capture automatique des erreurs et reporting de failures.
ProcessOrderJob.php
use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;
use Illuminate\Contracts\Queue\ShouldQueue;
class ProcessOrderJob implements ShouldQueue
{
public function handle(): void
{
// Track job start avec breadcrumb
ErrorReporter:: addBreadcrumb (
'Job processing started',
'job',
'info',
['order_id' => $this ->orderId, 'queue' => $this ->queue]
);
try {
$this ->processOrder();
} catch (\Exception $e) {
// Report job failure avec contexte
ErrorReporter:: reportError ($e, 'production', 500);
throw $e; // Re-throw pour Laravel
}
}
}
Middleware de monitoring
Créez un middleware pour traquer les actions utilisateur et surveiller les performances.
ErrorTracking.php
use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;
class ErrorTracking
{
public function handle($request, Closure $next)
{
$startTime = microtime (true);
// Track navigation path
ErrorReporter:: logNavigation ($request->path());
// Track user actions critiques
if ($request->isMethod('POST')) {
ErrorReporter:: logUserAction (
'Critical POST action',
['route' => $request->route()?->getName()]
);
}
$response = $next ($request);
// Monitor slow requests
$duration = ( microtime (true) - $startTime) * 1000;
if ($duration > 2000) {
ErrorReporter:: reportMessage (
'Slow request detected',
'production',
200,
null,
'warning',
['duration_ms' => $duration, 'route' => $request->path()]
);
}
return $response;
}
}
Exemple concret avec breadcrumbs
Exemple d'utilisation dans un processus de checkout avec gestion intelligente des breadcrumbs.
CheckoutController.php
use ErrorExplorer\LaravelErrorReporter\Facades\ErrorReporter;
use Illuminate\Validation\ValidationException;
class CheckoutController extends Controller
{
public function processPayment($userId, $amount)
{
// Track étape critique qui peut échouer
ErrorReporter:: addBreadcrumb (
'Payment process initiated',
'payment',
'info',
['user_id' => $userId, 'amount' => $amount]
);
try {
ErrorReporter:: addBreadcrumb ('Validating user', 'validation');
$user = $this ->validateUser($userId);
ErrorReporter:: addBreadcrumb (
'Processing payment',
'payment',
'info',
['amount' => $amount]
);
return $this->paymentService->charge($user, $amount);
} catch (ValidationException $e) {
ErrorReporter::reportMessage(
'User validation failed',
'production',
400,
null,
'error',
['user_id' => $userId, 'errors' => $e->errors()]
);
throw $e;
}
}
}
Error Explorer avec Express.js
Intégration complète avec Express pour capturer erreurs d'API et middleware.
Gestion Async/Await
Capture des erreurs dans les fonctions asynchrones.
Monitoring Performance
Surveillance des performances et métriques custom.
Error Boundaries React
Composants Error Boundary avec intégration Error Explorer.
Custom Hooks
Hooks personnalisés pour la gestion d'erreur.
Context API
Gestion globale des erreurs via Context.
Vue 3 Composition API
Intégration avec l'API de composition Vue 3.
Plugins Vue
Développement de plugins Vue avec Error Explorer.
Composants Vue
Gestion d'erreur dans les composants Vue.
PSR-3 Logging
Intégration avec les standards PSR-3.
Monitoring Mémoire
Surveillance de l'utilisation mémoire.
Gestion Exceptions
Capture et traitement des exceptions PHP.
Django Integration
Intégration avec Django framework.
Flask Integration
Intégration avec Flask microframework.
Python Asyncio
Gestion des erreurs avec asyncio.
Intégration WordPress avec Hooks
Utilisez les hooks WordPress pour intégrer Error Explorer dans votre site ou thème personnalisé.
functions.php
// Initialisation Error Explorer pour WordPress
add_action ('init', 'init_error_explorer');
function init_error_explorer() {
// Configuration Error Explorer
if ( function_exists ('error_explorer_init')) {
error_explorer_init ([
'dsn' => 'https://your-dsn@error-explorer.com/project',
'environment' => wp_get_environment_type(),
'release' => get_bloginfo('version'),
'user_context' => [
'id' => get_current_user_id(),
'username' => wp_get_current_user()->user_login ?? 'guest'
]
]);
}
}
// Hook pour capturer les erreurs fatales
add_action ('wp_fatal_error_handler', 'capture_fatal_errors');
function capture_fatal_errors($error) {
if ( function_exists ('error_explorer_capture_exception')) {
error_explorer_capture_exception ( new Exception($error['message']), [
'tags' => [
'wordpress' => get_bloginfo('version'),
'theme' => get_template(),
'type' => 'fatal_error'
],
'extra' => [
'file' => $error['file'] ?? 'unknown',
'line' => $error['line'] ?? 0,
'request_uri' => $_SERVER['REQUEST_URI'] ?? '/'
]
]);
}
}
Hook personnalisé pour actions utilisateur
user-actions.php
// Tracer les connexions utilisateur
add_action ('wp_login', 'track_user_login', 10, 2);
function track_user_login($user_login, $user) {
if ( function_exists ('error_explorer_add_breadcrumb')) {
error_explorer_add_breadcrumb ([
'message' => 'User logged in: ' . $user_login,
'category' => 'auth',
'level' => 'info',
'data' => [
'user_id' => $user->ID,
'user_role' => implode(', ', $user->roles),
'login_time' => current_time('mysql')
]
]);
}
}
Error Explorer pour Plugins WordPress
Intégrez Error Explorer dans vos plugins WordPress pour un debugging et monitoring avancé.
my-plugin.php
/**
* Plugin Name: Mon Plugin WordPress
* Description: Plugin avec intégration Error Explorer
* Version: 1.0.0
*/
class MyWordPressPlugin {
public function __construct() {
// Hook d'activation du plugin
register_activation_hook (__FILE__, [$this, 'activate']);
// Hooks principaux
add_action ('init', [$this, 'init']);
add_action ('wp_ajax_my_plugin_action', [$this, 'handle_ajax']);
}
public function activate() {
try {
// Création des tables ou configurations
$this->create_plugin_tables();
// Notification de succès à Error Explorer
if ( function_exists ('error_explorer_capture_message')) {
error_explorer_capture_message (
'Plugin activated successfully',
'info',
[
'plugin' => 'my-wordpress-plugin',
'version' => '1.0.0',
'wordpress_version' => get_bloginfo('version')
]
);
}
} catch (Exception $e) {
// Capture des erreurs d'activation
if ( function_exists ('error_explorer_capture_exception')) {
error_explorer_capture_exception ($e, [
'tags' => [
'plugin' => 'my-wordpress-plugin',
'context' => 'activation',
'severity' => 'high'
]
]);
}
throw $e;
}
}
public function handle_ajax() {
// Vérification de sécurité
if (! wp_verify_nonce ($_POST['nonce'], 'my_plugin_nonce')) {
wp_die ('Security check failed');
}
try {
// Logique métier du plugin
$result = $this->process_user_data($_POST['data']);
wp_send_json_success ($result);
} catch (Exception $e) {
// Capture des erreurs AJAX
if ( function_exists ('error_explorer_capture_exception')) {
error_explorer_capture_exception ($e, [
'tags' => ['ajax', 'plugin'],
'extra' => [
'action' => 'my_plugin_action',
'user_id' => get_current_user_id(),
'post_data' => $_POST
]
]);
}
wp_send_json_error ('Plugin error: ' . $e->getMessage());
}
}
}
// Initialisation du plugin
new MyWordPressPlugin();
Error Explorer pour Thèmes WordPress
Intégrez Error Explorer dans vos thèmes WordPress pour détecter et corriger les erreurs de template et de performance.
functions.php
/**
* Theme: Mon Thème WordPress
* Error Explorer Integration
*/
class ThemeErrorExplorer {
public function __construct() {
// Configuration du thème avec Error Explorer
add_action ('after_setup_theme', [$this, 'setup_theme']);
add_action ('wp_enqueue_scripts', [$this, 'enqueue_assets']);
add_action ('template_redirect', [$this, 'track_page_views']);
}
public function setup_theme() {
try {
// Support des fonctionnalités du thème
add_theme_support ('post-thumbnails');
add_theme_support ('custom-logo');
// Enregistrement des menus
register_nav_menus ([
'primary' => __('Primary Menu', 'my-theme'),
'footer' => __('Footer Menu', 'my-theme')
]);
} catch (Exception $e) {
// Capture des erreurs de configuration du thème
$this->capture_theme_error($e, 'theme_setup');
}
}
public function enqueue_assets() {
try {
// Chargement des styles et scripts
wp_enqueue_style (
'theme-style',
get_stylesheet_uri (),
[],
wp_get_theme ()->get('Version')
);
wp_enqueue_script (
'theme-script',
get_template_directory_uri () . '/assets/js/theme.js',
['jquery'],
wp_get_theme ()->get('Version'),
true
);
} catch (Exception $e) {
// Capture des erreurs de chargement d'assets
$this->capture_theme_error($e, 'asset_loading');
}
}
public function track_page_views() {
// Traçage des vues de pages pour analytics
if ( function_exists ('error_explorer_add_breadcrumb')) {
global $wp_query;
error_explorer_add_breadcrumb ([
'message' => 'Page viewed: ' . get_the_title(),
'category' => 'navigation',
'level' => 'info',
'data' => [
'page_id' => get_the_ID(),
'page_type' => $this->get_page_type(),
'template' => get_page_template_slug(),
'theme' => get_template(),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
]
]);
}
}
private function capture_theme_error($exception, $context) {
if ( function_exists ('error_explorer_capture_exception')) {
error_explorer_capture_exception ($exception, [
'tags' => [
'theme' => get_template(),
'context' => $context,
'wordpress' => get_bloginfo('version')
],
'extra' => [
'theme_version' => wp_get_theme()->get('Version'),
'template_hierarchy' => $this->get_template_hierarchy(),
'current_page' => get_the_ID()
]
]);
}
}
private function get_page_type() {
if ( is_front_page ()) return 'home';
if ( is_single ()) return 'single';
if ( is_page ()) return 'page';
if ( is_archive ()) return 'archive';
return 'other';
}
}
// Initialisation du gestionnaire d'erreurs du thème
new ThemeErrorExplorer();
Référence API
Documentation complète de l'API Error Explorer pour intégrer le reporting d'erreurs dans vos applications.
Endpoint Webhook
Headers requis
Headers
Content-Type: application/json
User-Agent: YourApp/1.0
Format du payload
payload.json
{
"message": "Call to undefined method User::getEmaill()",
"exception_class": "Error",
"stack_trace": "#0 /var/www/src/Controller...",
"file": "/var/www/src/Controller/UserController.php",
"line": 45,
"project": "mon-site-ecommerce",
"environment": "prod",
"http_status": 500,
"timestamp": "2025-06-02T14:30:25+02:00",
"fingerprint": "abc123...",
"request": {
"url": "https://monsite.com/profile",
"method": "GET",
"route": "user_profile",
"ip": "192.168.1.100",
"user_agent": "Mozilla/5.0..."
},
"server": {
"php_version": "8.2.7",
"memory_usage": 12582912
}
}
Réponses
Format Webhook
Structure des données JSON à envoyer à l'endpoint webhook :
Structure du webhook
Chaque webhook Error Explorer contient les informations suivantes :
Informations de l'erreur
message
string
Message d'erreur principal
exception_class
string
Classe de l'exception (ex: "Error", "Exception")
stack_trace
string
Stack trace complet de l'erreur
file
string
Chemin du fichier où l'erreur s'est produite
line
integer
Numéro de ligne de l'erreur
Contexte du projet
project
string
Nom du projet configuré
environment
string
Environnement (dev, staging, prod)
fingerprint
string
Hash unique pour regrouper les erreurs similaires
timestamp
string
Horodatage ISO 8601 de l'erreur
Contexte HTTP (optionnel)
request.url
string
URL de la requête qui a causé l'erreur
request.method
string
Méthode HTTP (GET, POST, etc.)
request.ip
string
Adresse IP du client
request.user_agent
string
User-Agent du navigateur
Exemples
Exemples pratiques d'intégration et d'utilisation d'Error Explorer dans différents contextes.
Capture d'erreur basique
basic-error.php
try {
// Code qui peut échouer
$user = User :: find ($id);
$email = $user-> getEmaill (); // Erreur de typo !
} catch ( Exception $e) {
// Erreur automatiquement rapportée à Error Explorer
throw $e; // Relance pour traitement local
}
Capture avec contexte custom
custom-context.php
// Ajouter du contexte personnalisé
ErrorExplorer :: addContext ([
'user_id' => auth ()-> id (),
'action' => 'payment_processing' ,
'order_id' => $order-> id
]);
Intégration avec logging existant
logging-integration.php
use Psr\Log\LoggerInterface;
class OrderService {
public function processOrder ($orderId) {
try {
// Logique de traitement
} catch ( Exception $e) {
// Error Explorer capture automatiquement
throw $e;
}
}
}
Dépannage
Solutions aux problèmes courants rencontrés lors de l'intégration et de l'utilisation d'Error Explorer.
Les erreurs n'apparaissent pas dans le dashboard
Solutions possibles :
- Vérifiez que
ERROR_REPORTING_ENABLED=true - Vérifiez l'URL webhook et le token
- Consultez les logs pour les erreurs HTTP
- Vérifiez que l'exception n'est pas dans la liste ignorée
Erreurs de connexion HTTP
Le SDK échoue silencieusement si le webhook est injoignable. Vérifiez vos logs :
Terminal
php bin/console log:search "Failed to report error"
Test de l'intégration
Créez une route de test pour vérifier l'intégration :
test-route.php
// Route de test
Route::get('/test-error-reporting', function () {
throw new \Exception('Test error for Error Explorer');
});