Best Practices for Error Handling in Production Server Code (example code)

Created at 18-Mar-2024 , By samar

When developing applications for production servers, it's crucial to implement robust error handling mechanisms to ensure smooth operation and prevent unexpected failures.

Here's an example of how to handle errors effectively in production server code in Laravel:

Create a wallet column in users table using migration command

php artisan make:migration add_wallet_column_to_users_table --table=users

Add code to migration file database\migrations\2024_03_18_053755_add_wallet_column_to_users_table.php and run php artisan migrate command to run migration after copy/paste code in it.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
     * Run the migrations.
    public function up(): void
        Schema::table('users', function (Blueprint $table) {

     * Reverse the migrations.
    public function down(): void
        Schema::table('users', function (Blueprint $table) {

Add below code to web.php file

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;

Route::get('/buy/{cookie}', function($cookie) {

    $validator  =   Validator::make(['cookie' => $cookie], [
                        'cookie' => 'required|integer|min:1'
        return 'Invalid number of cookies!';
    if (Auth::check()) {
        $wallet = Auth::user()->wallet;
        $purchaseAmount = $cookie * 1;
        if ($wallet < $purchaseAmount) {
            return 'Insufficient balance';
            User::where(['id' => Auth::user()->id])
                    ->update(['wallet' => ($wallet - $purchaseAmount)]);
            return 'Purchase successful!';
        }catch(Exception $e){
            throw new UnprocessableEntityHttpException($e->getMessage());
    } else {
        return  'You must be logged in to make a purchase!';

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.