How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Create a Custom Exception Class in Laravel (With Clean JSON Responses)
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Create a Custom Exception Class in Laravel (With Clean JSON Responses)
Web Development

How to Create a Custom Exception Class in Laravel (With Clean JSON Responses)

how7o
By how7o
Last updated: January 13, 2026
6 Min Read
Create custom exception class in Laravel (Artisan command + secure error handling)
SHARE

I used to handle errors in Laravel with random try/catch blocks everywhere. It worked… until it didn’t. One day I was building an API endpoint, and I realized every controller was returning a different error format. Some returned message, others returned error, some used 500 for everything (yikes).

Contents
  • Why create a custom exception in Laravel?
  • Step 1: Generate a custom exception class
  • Step 2: Define your custom exception (message + code + extra errors)
  • Step 3: Throw your custom exception anywhere
  • Step 4: Do you still need try/catch?
  • Cleaner alternative: handle it globally in Handler.php
  • Common mistakes (avoid these)
  • Related link
  • Final thoughts

That’s when I switched to a cleaner approach: create a custom exception class and let Laravel handle the response consistently. Once I did that, my controllers became simpler and my API responses became predictable.

Why create a custom exception in Laravel?

  • Cleaner code: remove repetitive try/catch blocks from controllers
  • Consistent API errors: same JSON structure everywhere
  • Better debugging: log/report specific failures with context
  • Reusable logic: throw the same error from services, jobs, controllers, etc.

Step 1: Generate a custom exception class

Laravel makes this easy with Artisan. Run:

php artisan make:exception CustomException

This will create a file inside app/Exceptions, usually like:

app/Exceptions/CustomException.php

Step 2: Define your custom exception (message + code + extra errors)

Here’s a practical version I use in real projects. It supports:

  • a human-readable message
  • an HTTP status code (like 400, 401, 403, 404, 422…)
  • an optional errors array (great for APIs)
<?php

namespace App\Exceptions;

use Exception;
use Throwable;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class CustomException extends Exception
{
    public array $errors;

    public function __construct(
        string $message = "Something went wrong.",
        int $code = 400,
        array $errors = [],
        ?Throwable $previous = null
    ) {
        parent::__construct($message, $code, $previous);
        $this->errors = $errors;
    }

    /**
     * Return a clean response.
     * For APIs this becomes JSON; for web you can customize as needed.
     */
    public function render(Request $request): JsonResponse
    {
        $status = $this->getCode();
        if (!is_int($status) || $status < 100) {
            $status = 400;
        }

        return response()->json([
            'error'   => true,
            'code'    => $status,
            'message' => $this->getMessage(),
            'errors'  => $this->errors,
        ], $status);
    }

    /**
     * Optional: log it your way (or skip this and rely on Laravel defaults)
     */
    public function report(): void
    {
        Log::warning($this->getMessage(), [
            'code' => $this->getCode(),
            'errors' => $this->errors
        ]);
    }
}

Tip: Don’t use HTTP 500 for everything. For “bad request” type issues, 400 or 422 is usually more correct.

Step 3: Throw your custom exception anywhere

Now you can throw it from controllers, services, jobs—wherever the error actually happens.

use App\Exceptions\CustomException;

if (!$condition) {
    throw new CustomException(
        "Invalid request data.",
        422,
        ['field' => ['This field is required.']]
    );
}

That’s the biggest win: you throw the error once, and Laravel takes care of formatting the response.

Step 4: Do you still need try/catch?

Most of the time, you don’t. If you throw a custom exception and it has a render() method, Laravel will convert it to a proper HTTP response automatically.

But if you want to handle it manually in a specific place, you can still catch it:

use App\Exceptions\CustomException;

try {
    // risky logic here
} catch (CustomException $e) {
    return response()->json([
        'error' => true,
        'message' => $e->getMessage(),
    ], 500);
}

Personally, I only do this when I need a very specific fallback behavior. Otherwise, I let the exception handle itself via render().

Cleaner alternative: handle it globally in Handler.php

If you prefer keeping exceptions “dumb” and handling responses in one place, you can register a handler in:

app/Exceptions/Handler.php

Example (inside the register() method):

use App\Exceptions\CustomException;
use Illuminate\Http\Request;

public function register(): void
{
    $this->renderable(function (CustomException $e, Request $request) {
        return response()->json([
            'error'   => true,
            'code'    => $e->getCode() ?: 400,
            'message' => $e->getMessage(),
            'errors'  => $e->errors ?? [],
        ], $e->getCode() ?: 400);
    });
}

This is nice if you plan to create multiple custom exceptions and want the same JSON format across all of them.

Common mistakes (avoid these)

  • Returning 500 for everything: use 422 for validation-like issues, 404 for missing resources, etc.
  • Forgetting to reboot your response format: define one JSON structure and stick to it.
  • Throwing exceptions for normal flow: exceptions should be “something went wrong,” not “this is expected behavior.”
  • Not logging context: if it helps debugging, include useful details in report().

Related link

  • How to manually return or throw an error/exception in Laravel

Final thoughts

Once I started using custom exception classes in Laravel, my code got noticeably cleaner. Instead of juggling different error responses in controllers, I now throw meaningful exceptions and let Laravel return a consistent response every time. If you’re building an API, this is one of the fastest ways to make your app feel professional.

TAGGED:apiArtisanbackenderror handlingexception handlingjson responseLaravelphp

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Migrating files from cPanel to aaPanel using rsync cPanel to aaPanel Migration with rsync: Fix Permissions, SSH Port, and CSF Firewall
Next Article Fix 409 Conflict error in Laravel (cookies, cache, WAF) How I Fixed the 409 Conflict Error in Laravel (Cookie / Browser / WAF Fix)
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Laravel get config variable — config() helper and Config facade resolving dotted keys
Web Development

How to Get Config Variables in Laravel

7 Min Read
WordPress prepare LIKE SQL — %s placeholder + % wildcards in the value
Web Development

How to Prepare a %LIKE% SQL Statement in WordPress

7 Min Read
Get the first character of a JavaScript string
Web Development

How to Get the First Character of a String in JavaScript

5 Min Read
Remove unwanted characters from a PHP string with regex
Web Development

How to Remove Unwanted Characters from a String in PHP

5 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?