Devo gestire TokenMismatchException
in laravel 5 in modo tale che se il token non corrisponde visualizzerà un messaggio all'utente al posto dell'errore TokenMismatchException
.Handle TokenMismatchException in laravel 5
7
A
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);
}
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');
}
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
Puoi aggiungere 'var_dump ($ e); die(); 'prima dell'istruzione' if' per verificare se il metodo 'rendered' è chiamato o meno. –
Sì, ora ho il dump della pagina dirty dell'oggetto (Illuminate \ Session \ TokenMismatchException) # 274 ... – TechyTimo