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

Ligonsker's avatar

DB transaction - throw exception and also return error message to the user

Is it possible to both throw an exception (Which outputs to the logs), and also return a message to the user?

try {
    DB::beginTransaction();
    // some queries here...
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw new \Exception('Some error');
    // But also return a message to the front end to display to the user
}

Is it as simple as adding a return below the throw?

0 likes
3 replies
LaryAI's avatar
Level 58

Yes, it is possible to both throw an exception and return a message to the user. You can catch the exception and then return a response with the error message. Here's an example:

try {
    DB::beginTransaction();
    // some queries here...
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw new \Exception('Some error');
    // But also return a message to the front end to display to the user
    return response()->json(['error' => 'Something went wrong. Please try again.'], 500);
}

In this example, we catch the exception and rollback the transaction. Then, we throw a new exception to log the error. Finally, we return a JSON response with an error message and a 500 status code. You can customize the error message and status code to fit your needs.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

If you throw a new error (or rethrow) then the response won't be send to the user since the unhandled exception flow will be followed.

just catch and respond according to your situation (eg view with error or API response)

1 like
Ligonsker's avatar

@Snapey So if I wanted to both save the error in the logs and send to the user I would do something like:

Log::debug($exception);
return ('error..');

?

Please or to participate in this conversation.