Custom Exception in Laravel

Mohammad Roshandelpoor
3 min readJul 6, 2024

--

In Laravel, custom exceptions allow developers to manage errors effectively. By extending the base Exception class, developers can craft personalized exception classes with error messages and added features. This method improves the clarity and upkeep of the code and enhances user satisfaction by offering clear and meaningful error messages. Exception handling is an essential aspect of any robust application, and Laravel makes it easier by providing a variety of built-in exception classes.

Step 1: Create a Custom Exception Class

In Laravel, creating a custom exception involves defining a new class that extends the base Exception class or any of its subclasses, such as HttpException or ModelNotFoundException. Let's create a sample custom exception called CustomException:

<?php

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
// Additional custom exception logic can be added here
}

Step 2: Throwing the Custom Exception

Once the custom exception class is defined, you can throw it in your application code when a specific error condition is encountered. For example:

<?php

namespace App\Http\Controllers;

use App\Exceptions\CustomException;

class UserController extends Controller
{
public function getUser($id)
{
if (!$id) {
throw new CustomException('User ID is required.');
}

// Other user retrieval logic
}
}

Step 3: Handling the Custom Exception

To handle the custom exception, you can use the try-catch block in your application code to catch the specific custom exception and respond accordingly:

<?php

namespace App\Http\Controllers;

use App\Exceptions\CustomException;

use Illuminate\Http\Request;

class UserController extends Controller
{
public function getUser(Request $request, $id)
{
try {

// User retrieval logic

} catch (CustomException $e) {

return response()->json(['error' => $e->getMessage()], 400);

}
}
}

Sample Implementation

Let’s consider a scenario where we want to throw a custom exception when a user with a specific role tries to access a restricted resource. We can create a custom exception class called UnauthorizedAccessException and throw it when the access is denied.

<?php

namespace App\Exceptions;

use Exception;

class UnauthorizedAccessException extends Exception
{
// Additional custom exception logic can be added here
}

In the controller, we can check the user’s role and throw the custom exception if the access is unauthorized:

<?php

namespace App\Http\Controllers;

use App\Exceptions\UnauthorizedAccessException;

use Illuminate\Http\Request;

class ResourceController extends Controller
{
public function viewResource(Request $request, $id)
{
if (!$request->user()->hasRole('admin')) {

throw new UnauthorizedAccessException(
'Access denied. Admin role required.'
);

}

// View resource logic
}
}

Conclusion

Using custom exceptions, in Laravel, enables you to effectively manage errors that are specific to your application. By following the guidelines provided in this article and utilizing custom exceptions within your Laravel project, you can enhance error handling. Enhance the user experience. Custom exceptions offer an approach, to addressing situations, ultimately enhancing the stability and sustainability of your Laravel application.

Feel free to Subscribe for more content like this 🔔, clap 👏🏻 , comment 💬, and share the article with anyone you’d like

And as it always has been, I appreciate your support, and thanks for reading.

Connect with me:

LinkedIn: https://www.linkedin.com/in/roshandelpoor/

--

--

Mohammad Roshandelpoor

Software Engineer | Laravel | PHP | Nuxt | Vue | with over 10 years of experience, have a deep understanding of software architecture