📊 Capítulo 04: Middlewares & Exceções no Laravel
Especialização Backend com PHP & Laravel
🗺️ Configuração de Middlewares e Exceções no Laravel 11 (bootstrap/app.php)
flowchart TD
BOOT["bootstrap/app.php"]
--> WITH_MW["->withMiddleware(function (Middleware $middleware) { ... })"]
WITH_MW --> ALIAS["$middleware->alias(['admin' => EnsureUserIsAdmin::class])"]
WITH_MW --> STATELESS["$middleware->statefulApi()"]
BOOT --> WITH_EX["->withExceptions(function (Exceptions $exceptions) { ... })"]
WITH_EX --> RENDER["$exceptions->render(function (CustomException $e) { return response()->json(...); })"]
style BOOT fill:#ede7f6,stroke:#512da8,stroke-width:2px
style WITH_MW fill:#fff3e0,stroke:#ff9800,stroke-width:2px
style ALIAS fill:#e8f5e9,stroke:#4caf50,stroke-width:1.5px
style STATELESS fill:#e1f5fe,stroke:#03a9f4,stroke-width:1.5px
style WITH_EX fill:#ffebee,stroke:#d32f2f,stroke-width:2px
style RENDER fill:#c8e6c9,stroke:#2e7d32,stroke-width:1.5px
🎯 Slide 1: Estrutura de um Middleware no Laravel
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ForcarRespostaJson {
public function handle(Request $request, Closure $next): Response {
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
🎯 Slide 2: Tratamento Fluente de Erros no Laravel 11
// No bootstrap/app.php
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (SaldoInsuficienteException $e, Request $request) {
return response()->json([
'erro' => 'Operação recusada',
'detalhe' => $e->getMessage(),
], 422);
});
})
🎯 Slide 3: Respostas Padronizadas em JSON para APIs
- O Laravel detecta automaticamente requisições com header
Accept: application/jsone nunca redireciona para páginas HTML em erros 401 ou 422!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim