i'm using DB::transaction() for my code and it's working fine, also tested a possible error with unmatching IDs from two related tables. But in case any unexpected error happens and the transaction prevents it, how could i display an error message to the user instead of laravel error?
My code looks like this
DB::transaction(function() {
DB::table('table1')->insert([ // some data insert ]);
DB::table('table2')->insert([ // some data insert ]); }
I was wondering if i could wrap it in to a try catch like this:
try {
DB::transaction(function() {
DB::table('table1')->insert([ // some data insert ]);
DB::table('table2')->insert([ // some data insert ]);
} catch (Exception $e) {
return redirect->back()->with('error', error message)
}
And also i have this code in a command that executes every 10 min, could i do the same thing but instead of returning an error message (because no user would see it) send an email to admins that there is an error? Something like:
public function handle() {
try {
DB::transaction(function() {
DB::table('table1')->insert([ // some data insert ]);
DB::table('table2')->insert([ // some data insert ]);
} catch (Exception $e) {
Mail::to('adminmail')->send('$error_message');
}
}
Which way should i go for?
CodePudding user response:
The answer is yes of course you can add a try/catch for this problem, since you plan to put this login in a cronjob there is no need to return any error message to the application, so the better option is to email the Admin with the error message, so this logic should work
public function handle() {
try {
DB::transaction(function() {
DB::table('table1')->insert([ // some data insert ]);
DB::table('table2')->insert([ // some data insert ]);
}
} catch (Exception $e) {
Mail::to('adminmail')->send($e->getMessage());
}
}
Also if you do not want to spam the admin with every error message every 10 mintues, you can add Sentry for error handling inside the app (it does cost a bit but its a life saver);