Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sarmadindhar's avatar

Custom exception handling only for api routes

Hello all How can I create the custom exception handlers for api routes only Currently the exception handlers are applying on both api and web routes My api routes begin wih the api prefix eg: api/signup

0 likes
1 reply
bobbybouwmann's avatar

Well it depends on the errors you throw! If you throw an exception with a parent of HttpException it will be handled as an HTTP response. So that's whenever you get a 404 or 403 and so on. So this is something you should think about.

Anyway for generic exceptions you also get the request class in Laravel. So the exceptions class has a method called prepareResponse which is not by default in the app/Exceptions/Handler.php because it's hidden in a parent class. However you can override this method, check for api request and return accordingly.

public function prepareResponse($request, Exception $exception)
{
    if ($request->isJson()) {
        $body = [
            'message' => $exception->getMessage(),
        ];

        return response()->json($body, $exception->getStatusCode(), $exception->getHeaders());
    }

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

Something like this should do. I hope I point you in the right direction ;)

Please or to participate in this conversation.