Skip to content
Advertisement

How to pass error handling to a function in PHP?

I need to handle multiple types of error in many places in my PHP class in my Laravel project, and of course I don’t want to repeat error handling codes everywhere in my code.

I have this code now:

class MyAwesomeClass {
    public function parseItems(Request $request) {
        // do something

        try {
            // ...
        } catch (Exception $error) {
            $this->handleError($error);
        }
    }

    public function handleError(Exception $error) {
        $type = get_class($error);

        switch ($type) {
            case 'TypeAException':
                return response([
                    'message' => 'My custom message for Type A error',
                    'status' => 'Error',
                    'errors' => []
                ], 500);

            case 'TypeBException':
                return response([
                    'message' => 'My custom message for Type B error',
                    'status' => 'Error',
                    'errors' => []
                ], 500);

            default:
                // ...
                break;
        }
    }
}

But the handleError() method isn’t called.

How can I pass the exceptions to my error handler method in PHP?

Advertisement

Answer

In Laravel, error and exception handling is already configured for you. No need to use custom class to achieve this.

All exceptions are handled by the AppExceptionsHandler class, you may customize report and render methods on this class:

/**
 * Render an exception into an HTTP response.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  Throwable  $exception
 * @return IlluminateHttpResponse
 */
public function render($request, Throwable $exception)
{
    if ($exception instanceof TypeAException) {
        return response([
            'message' => 'My custom message for Type A error',
            'status' => 'Error',
            'errors' => []
        ], 500);
    }
    else if ($exception instanceof TypeBException) {
        return response([
            'message' => 'My custom message for Type B error',
            'status' => 'Error',
            'errors' => []
        ], 500);
    }

    return parent::render($request, $exception);
}

See Error Handling on Laravel docs for more info.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement