[LARAVEL] global exception - fourslickz/notes GitHub Wiki

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Http\Response;

class Handler extends ExceptionHandler
{
    public function render($request, Throwable $exception)
    {
        // Example of handling a specific exception type
        if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
            return response()->json(['error' => 'Resource not found'], Response::HTTP_NOT_FOUND);
        }

        // Handle other exceptions here
        return parent::render($request, $exception);
    }
}

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Throwable;

class ExampleController extends Controller
{
    public function exampleMethod(Request $request)
    {
        try {
            // Your code that may throw an exception
            $data = SomeModel::findOrFail($request->id);
            return response()->json($data);
        } catch (Throwable $e) {
            // Delegate to the global exception handler
            return app(\App\Exceptions\Handler::class)->render($request, $e);
        }
    }
}