What are best practices for error handling in PHP when using PHPMailer or other libraries?

When using PHPMailer or other libraries in PHP, it's important to implement proper error handling to ensure that any issues with sending emails are gracefully handled. One best practice is to use try-catch blocks to catch any exceptions thrown by the library and handle them accordingly, such as logging the error or displaying a user-friendly message.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    // Send email code here
    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}