Home > other >  Why 500 error is not catched in try block?
Why 500 error is not catched in try block?

Time:10-04

In laravel 8 / livewire App I make component for user registration and when I have 500 error, the error is not catched in try block, as I expected, but I got common laravel modal dialog with error description. In my app/Http/Livewire/Register.php :

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Sentinel;
use App\Models\User;
use DB;

class Register extends Component
{
    public $form
        = [
            'name'           => 'newuser',
            'email'       => '[email protected]',
            'password'            => '111111',
            'password_2'            => '111111',
            'first_name'         => 'Fname',
            'last_name'         => 'Lname',
        ];

    public function render()
    {
        return view('livewire.register')
            ->layout('layouts.frontpage');
    }


    public function store()
    {
        $this->validate(User::getUserRegisterValidationRulesArray(null), User::getValidationMessagesArray());

        \Log::info('-2 store $this->form ::' . print_r($this->form, true));

        try {
            DB::beginTransaction();
            $newUser = Sentinel::registerAndActivate([
                'username' => $this->form['name'],  // in db I have name field, so that raise runtimeerror!
                'email'    => $this->form['email'],
                'password' => $this->form['password']
            ]);

            DB::commit();
            $this->dispatchBrowserEvent('FrontendPageMessageSuccess', [
                'title'     => 'Registration',
                'message'   => 'You were successfully registered !'
            ]);

        } catch (Exception $e) {
            DB::rollBack(); // THIS BLOCK IS NOT RUN!
            $this->dispatchBrowserEvent('FrontendPageMessageWarning', [
                'title'     => 'Registration',
                'message'   => 'Registration error : ' . $e->getMessage()
            ]);

        }       
    } // public function store()

printscreen : https://prnt.sc/1umpnzb

How can it be fixed ?

Thanks!

CodePudding user response:

The error said

Field name doesn't have a default value

that's happen because you pass username instead of name so you need to fix it like this

$newUser = Sentinel::registerAndActivate([
  'name' => $this->form['name'],
  'email'    => $this->form['email'],
  'password' => $this->form['password']
]);

if you want to catch this error you need to edit the catch block and change the Exception to QueryException instead

use Illuminate\Database\QueryException;

try {
   //
} catch(QueryException $e) {
  //
}
  • Related