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?
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.