2015-08-06 12 views

risposta

20

È possibile creare un numero personalizzato exception render nella classe App\Exceptions\Handler (nel file /app/Exceptions/Handler.php).

Ad esempio, per rendere una visione diversa, quando per l'errore TokenMismatchException, è possibile modificare il metodo di render a qualcosa di simile:

/** 
* Render an exception into an HTTP response. 
* 
* @param \Illuminate\Http\Request $request 
* @param \Exception $e 
* @return \Illuminate\Http\Response 
*/ 
public function render($request, Exception $e) 
{ 
    if ($e instanceof \Illuminate\Session\TokenMismatchException) { 
     return response()->view('errors.custom', [], 500); 
    } 
    return parent::render($request, $e); 
} 
+0

Ciao Hiew. Ho appena provato il tuo metodo e sfortunatamente ottengo ancora un "TokenMismatchException in VerifyCsrfToken.php line 53" ogni volta che pubblico un falso csrf token/ – TechyTimo

+0

Puoi aggiungere 'var_dump ($ e); die(); 'prima dell'istruzione' if' per verificare se il metodo 'rendered' è chiamato o meno. –

+0

Sì, ora ho il dump della pagina dirty dell'oggetto (Illuminate \ Session \ TokenMismatchException) # 274 ... – TechyTimo

6

Avrete bisogno di scrivere una funzione di rendere l'errore TokenMismatchException. Aggiungerai questa funzione alla tua classe App \ Exceptions \ Handler (nel file /app/Exceptions/Handler.php) in questo modo:

// make sure you reference the full path of the class: 
use Illuminate\Session\TokenMismatchException; 

class Handler extends ExceptionHandler { 

    protected $dontReport = [ 
     HttpException::class, 
     ModelNotFoundException::class, 
     // opt from logging this error to your log files (optional) 
     TokenMismatchException::class, 
    ]; 

    public function render($request, Exception $e) 
    { 
     // Handle the exception... 
     // redirect back with form input except the _token (forcing a new token to be generated) 
     if ($e instanceof TokenMismatchException){ 
      return redirect()->back()->withInput($request->except('_token')) 
      ->withFlashDanger('You page session expired. Please try again'); 
     } 
+0

Grazie, questo funziona eccetto che l'istanza deve avere il percorso completo: 'if ($ exception instanceof \ Illuminate \ Session \ TokenMismatchException) {' – Guillaume

+0

Si noti che faccio riferimento al percorso completo della classe in alto – TechyTimo