How to Manually Return or Throw an Error/Exception in Laravel?

In my Laravel project, I need to throw an error or exception manually. I have a service class where I want to throw an exception and catch it in my controller using a try-catch block. Can someone guide how to achieve this?

You can also throw custom exceptions using the throw keyword. For instance:

throw new \Exception('Something went wrong');

Or You can also try throw_if If you need to check condition.

throw_if(
      <condition>,
      new \Exception('Something went wrong')
  );

Here’s how you can do it in your service class:

<?php

namespace App\Services;

class MyService
{
    public function someMethod()
    {
        // Check if some condition is not met
       throw_if(
           <condition>,
           new \Exception('Something went wrong')
       );

        // If condition is met, continue with your code
    }
}

Then, in your controller, you can catch this exception using a try-catch block:

<?php

namespace App\Http\Controllers;

use App\Services\MyService;
use Illuminate\Http\Request;

class MyController extends Controller
{
    public function myMethod(Request $request, MyService $myService)
    {
        try {
            // Call the method from your service class
            $myService->someMethod();

            // If no exception is thrown, continue with your code
        } catch (Exception $e) {
            // Handle the exception
            // You can log the error, return a custom response, or perform any other actions
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}

You can use different Exception listed below.

use Illuminate\Validation\ValidationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Access\AuthorizationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Database\Eloquent\ModelNotFoundException;

Creating Our Own Exception Class

Now that you know how to use Exception, You can try using your own exception.

Read this topic.