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

ronon's avatar
Level 9

Throw exception with specifc status code? (Misunderstanding?)

Currently my understanding of Exceptions is, that if you have a custom exception like: DontKnowException

<?php

namespace App\Exceptions;

use Exception;

class DontKnowException extends Exception
{
    //
}

and you pass a code to it when you throw it

                throw new DontKnowException('Dont know what youre trying todo....', 412);

the exception should return the message with the provided 412 statuscode, or not? I currently always receive a 500 statuscode.

I'm currently on v5.8

0 likes
3 replies
bobbybouwmann's avatar

An exception is always a 500 HTTP status code. An exception basically tells you that something broke in your application and you need to take action on it.

Luckily you can catch exceptions and perform some other action. In your case, you should catch the exception in your app/Exceptions/Handler.php and perform some action

// app/Exceptions/Handler.php

public function render($request, Throwable $exception)
{
    if ($exception instanceof DontKnowException) {
        abort(412, $exception->getMessage());
    }

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

Documentation: https://laravel.com/docs/7.x/errors#render-method

1 like
Artwork's avatar

Please be aware that the abort will call the whole main handler again, which in turn may log and notify about the same or another exception, including a possible duplicate.

ronon's avatar
Level 9

Feeling dump now. On other exceptions I override the render method, don't know why I thought what I wrote

Please or to participate in this conversation.