laravellaravel-exceptions

How to catch custom error raised in method of object?


On laravel 9 site in my custom class method raise custom error with error message

<?php

    class CustomClass
    {
    
        use Illuminate\Database\Eloquent\ModelNotFoundException;
        use Illuminate\Http\Exceptions\HttpResponseException;
        ...
        public function method(): array
        {
    
        if(false) {
            throw new HttpResponseException(response()->json([
                'message' => $validated['message'],
            ], 422));
        }

but I failed to catch this error in control where methods raised :

{
    try {
        $imageUploadSuccess = $customClass->method(
            ...
        ); // This method can raise different types of exception
    }
    catch (ModelNotFoundException $e) { // exception with invalid id is catched - THIS PART WORKS OK 
        return response()->json([
            'message' => 'Item  not found',
        ], 404);
    }
    catch (HttpResponseException $e) { //  I catch HttpResponseException with is generated in method
        // None of these 2 methods returns custom error message in method :
        \Log::info($e->getMessage()); // empty value - I NEED TO GET THIS MESSAGE TEXT
        \Log::info($e->getCode());    // 0 value
        \Log::info($e->getTraceAsString());
        return response()->json([
            'message' => $e->getMessage(),
        ], 422);
    }
    return response()->json(['success' => true],  400);

Have I to use other class, not HttpResponseException ? I which way ?

Thanks in advance!


Solution

  • You’re not throwing your custom exception so it’s never raised so it won’t be catchable.

    Replace where you throw the HttpResponseException with your Exception.

    <?php
    
    class CustomClass
    {
        public function method()
        {
            $isValid = false;
            if(!$isValid) {
                throw new SomeCustomException(response()->json([
                    'message' => $validated['message'],
                ], 422));
            }
        }
    }
    

    You would then use do something like:

    $customClass = new CustomClass();
    $customClass->method();
    

    Note how I have defined a variable $isValid and how I check it for a true or false value in the if statement. This is because if checks for truthy values and false will never be `true so your custom exception would never be thrown.

    if (false) {
        // code in here will never execute
    }