For a project (which is about estate properties) i have included a contact form where a visitor can contact an estate broker if the visitor is interested to buy/hire an estate property.
I am using Symfony2 and its library. For the contact mail, i am using the Swiftmailer library.
Well, i have the next code which handles the form submit. there, I create a mail object to be able to send mails. It works, but i want to provide a error resolving service if there are problems with the smtp host from sender/receiver.
Here is the code,
$data = $contactForm->getData();
try {
// create body text
$body = $app['twig']->render('mailTemplate.twig', array('data' => $data, 'immoid' => $immoID));
// set mail
$mail = \Swift_Message::newInstance()
->setSubject('Contact reaction on your immo offer.')
->setFrom($app['swiftconfig']['sender'])
->setTo($contactinfo['contactmail'])
->setBody($body, 'text/html');
// send mail
$app['mailer']->send($mail);
// redirect if successfull
$app->redirect($app['url_generator']->generate('immoDetail', array('immoID' => $immoID)));
}
catch (Swift_TransportException $STe) {
// logging error
$string = date("Y-m-d H:i:s") . ' - ' . $STe->getMessage() . PHP_EOL;
file_put_contents("errorlog.txt", $string, FILE_APPEND);
// send error note to user
$errorMsg = "the mail service has encountered a problem. Please retry later or contact the site admin.";
}
catch (Exception $e) {
// logging error
$string = date("Y-m-d H:i:s") . ' - GENERAL ERROR - ' . $e->getMessage() . PHP_EOL;
file_put_contents("errorlog.txt", $string, FILE_APPEND);
// redirect to error page
$app->abort(500, "Oops, something went seriously wrong. Please retry later !");
}
($app['swiftconfig']['sender'] = mailaddress from host / $contactinfo['contactmail'] = mailaddress from site visitor (submitted in contact form))
Now, when the smtp host doesn't work, Swiftmailer DOES send an exception, but the try-catch block ISN'T catching it. The function is just being continued.
Even the root try-catch block (in app.php) isn't catching it too. As a result of this, you see a large PHP error on the webpage, which shouldn't happen. The message from it is described here below,
SCREAM: Error suppression ignored for
---
Fatal error: Uncaught exception 'Swift_TransportException' with message ' in C:\...\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php on line 266
---
Swift_TransportException: Connection could not be established with host <output omitted>
Does anyone know why the try catch block isn't catching the custom exception ? I have investigated the class files and the progress, but i don't see any unusual activity.
I hope that someone can come with a solution to this because PHP errors shouldn't appear on site pages.
remove from your config.yml
spool: { type: memory }
Then you will be to add try catch like this
try{
$mailer = $this->getMailer();
$response = $this->getMailer()->send($message);
}catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
Try to put a backslash infront of Exception.
catch(\Exception $e)
A \ (backslash) before the beginning of a class name represents the Global Namespace.
Using a backslash will ensure that the Exception is called within the global namespace.
When you do $app['mailer']->send($mail); the email message is not being sent at that point if you have spooling turned on. See http://symfony.com/doc/current/cookbook/email/spool.html
If you have the default setting of spool: { type: memory }, the \Swift_TransportException will be thrown during the kernel termination phase, after you controller has exited.
One way around this is to turn off the spooling (but then your users might have to wait while the email is sent), or you can make your own eventlistener to handle the exception. http://symfony.com/doc/current/cookbook/service_container/event_listener.html
I ran into this problem in Laravel 4.2 when I added a SwiftMailerHandler to Monolog so it would email to me anything logged at a certain level or above. There was no way for me to catch the exception in the handler and it was thrown back to the browser. I solved it by subclassing SwiftMailerHandler:
<?php
/*******************************************************************************
* $Id: LogMailer.php 12152 2015-09-15 00:42:38Z sthames $ */
/**
* Subclass of Monolog SwiftMailerHandler that will catch exceptions SwiftMailer
* throws during the send. These exceptions are logged at the critical level.
* Without this, such exceptions are reported back to the browswer.
*******************************************************************************/
class LogMailer extends \Monolog\Handler\SwiftMailerHandler
{
/** Flag set when logging an exception during send. */
protected $dont_mail = false;
/** Overloads sender to catch and log errors during the send. */
protected function send($content, array $records)
{
try
{
if (!$this->dont_mail)
parent::send($content, $records);
}
catch(\Exception $e)
{
$this->dont_mail = true;
Log::critical($e->getMessage());
$this->dont_mail = false;
}
}
}
This handler catches the SwiftMailer exception and logs it at the critical level so it's not lost. I don't get an email about it but at least it's in the log.
I was surprised to find SwiftMailerHandler offered no way to inject an exception handler into the send method but fortunately the code is written well enough to make this solution pretty simple.
Works great and has given me no trouble so far.
Sure you have the latest version of swiftmailer? Line 226 of StreamBuffer.php doesn't throw any exception. This version from 2 years ago does throw the exception on that specific line.
I'd try running the latest version before diving into the issue more deeply.
SCREAM is a setting of XDebug that allows to see errors that are normally caught or suppressed. (Using #, for example.) Search for
xdebug.scream = 1
in your php.ini and set this to 0.
you can try below code for custom error:
public function render($request, Exception $exception)
{
if ($exception instanceof \Swift_TransportException) {
return response()->view('errors.404');
}
return parent::render($request, $exception);
}
Related
I want to set a custom message to be displayed to the user when I throw an error in Laravel 5.1. For example, in a controller I might have:
if(!has_access()){
abort('401', 'please contact support to gain access to this item.');
}
Then my custom error page I would display the error with:
$exception->getMessage();
However, what if there was a SQL error or other event? Wouldn't that also set the Exception Message which I would be unknowingly outputting on my error page?
The PHP docs for getMessage() don't go into much detail about this.
How can I set a specific exception message without introducing any security risk?
However, what if there was a SQL error or other event? Wouldn't that also set the Exception Message which I would be unknowingly outputting on my error page?
Potentially, yes. PHP makes no guarantees that the contents of exception messages will be "safe" to display to users, and it's quite likely that some classes will throw exceptions which include sensitive information in the message.
If you want to use exceptions to display errors to users, use a specific subclass of Exception for those exceptions, and only print the message if the exception was an instance of that subclass, e.g.
class UserVisibleException extends Exception {
// You don't need any code in here, but you could add a custom constructor
// if you wanted to.
}
// Then, in your abort() function...
throw new UserVisibleException($message);
// Then, in your exception handler...
if ($exc instanceof UserVisibleException) {
print $exc->getMessage();
} else {
print "An internal error occurred.";
}
If you access your app.php file:
'debug' => env('APP_DEBUG', false),
In your production env, set this to false. This would make sure that no debug errors would be displayed in the production environment.
Once this is set, you can respond to normal exceptions through your controller. Anything else, laravel wouldn't display the error page.
Yes,
$e->getMessage() can potentially reveal more information about your code IF you use it in a similar way:
try {
$executeSomethingHereForWhichYouExpectAnException();
// Basic \Exception that reports everything
} catch (\Exception $e) {
$error = $e->getMessage();
}
even with 'debug' => false in app.php. For example if you have an error with your code $error would display it - basically ANY type of error (PHP,MYSQL,ETC);
However, there is a fix - to catch your CustomException messages and prevent typical error displaying if you use it in like so:
try {
$executeSomethingHereForWhichYouExpectAnException();
// Our custom exception that throws only the messages we want
} catch (\CustomException $e) {
// Would contain only 'my_custom_message_here'
$error = $e->getMessage();
}
What is the difference you may ask - the difference is that instead of \Exception which is the basic error reporting, we use \CustomException class, which you throw from $executeSomethingHereForWhichYouExpectAnException() function:
executeSomethingHereForWhichYouExpectAnException(){
if (something) {
throw new CustomException("my_custom_message_here", 1);
}
}
If you have more exceptions you can include them like so (as of PHP7.1):
try {
something();
} catch(\CustomException | \SecondCustomException $e) {
// custom exceptions
} catch(\Exception $e) {
// basic exception containing everything
}
I followed a tutorial and looked Laravel's docs for registering a custom error handler.
I register the class, and throw MyCustomException, but for some reason, it ignores everything in it and just runs the regular Exception class. The code below prints out exception 'MyCustomException' with message 'This is NOT the message I want to see' instead of "This is the custom exception message"
Currently all the code below is just on a test page, but I've tried registering the class (and putting the MyCustomException declaration) into global.php before Exception and I've tried after Exception as well. Nothing changes.
I've tried sleep(10) inside of MyCustomException too, and that doesn't get run; MyCustomException just doesn't get run.
What am I doing wrong?
Edit: in fact, copying and pasting the code from the tutorial results in the same thing as my custom code; the custom exception handler doesn't get run.
class MyCustomException extends Exception {}
App::error(function(MyCustomException $exception) {
return "This is the custom exception message.";
});
//Now throw the error and see what comes out
try {
throw new MyCustomException('This is NOT the message I want to see');
} catch (MyCustomException $e) {
die($e);
}
please try like this
throw new MyCustomException('This is NOT the message I want to see');
You've probably solved this by now, but what you want is $e->getMessage().
With PHP 5.1+ that will print your exception message.
Docs: http://php.net/manual/en/exception.getmessage.php
I am developing a simple mailing application with Gmail account as host.It works like a charm but the problem rises when send() function throw an exception.
I see that try catch statement can't handle the exception.
It doesn't work even when I use Global exception class.
this question discussed in somewhere also .
for example :
Catch swiftmailer exception in Symfony2 dev env controller
or
https://groups.google.com/forum/#!topic/symfony2/SlEzg_PKwJw
but they didn't reach a working answer.
My controller function code is :
public function ajaxRegisterPublisherAction()
{
//some irrelevant logic
$returns= json_encode(array("username"=>$username,"responseCode"=>$responseCode));
try{
$message = \Swift_Message::newInstance()
->setSubject('hello world')
->setFrom('jafarzadeh91#gmail.com')
->setTo('jafarzadeh991#yahoo.com')
->setBody(
$this->renderView('AcmeSinamelkBundle:Default:email.txt.twig',array('name'=>$username,"password"=>$password))
);
$this->container->get("mailer")->send($message);
}
catch (Exception $e)
{
}
return new \Symfony\Component\HttpFoundation\Response($returns,200,array('Content-Type'=>'application/json'));
}
The response that sent from above code that I receive in firebug console is :
{"username":"xzdvxvvcvxcv","responseCode":200}<!DOCTYPE html>
<html>
.
.
Swift_TransportException: Connection could not be established with host smtp.gmail.com [Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?]
.
.
</html>
and I catch my hairs because I don't know why the kernel handle the exception in continue of my json object?
when I comment this line:
$this->container->get("mailer")->send($message);
the exception doesn't occur and I have a valid json in client side.(that is matter-of- course although)
I changed Exception to \Exception or \Swift_TransportException or even Swift_TransportException ! but no good result.
When you do $this->container->get("mailer")->send($message); the email message is not being sent at that point if you have spooling turned on. See http://symfony.com/doc/current/cookbook/email/spool.html
If you have the default setting of spool: { type: memory }, the \Swift_TransportException will be thrown during the kernel termination phase, after your controller has exited.
One way around this is to turn off the spooling (but then your users might have to wait while the email is sent), or you can make your own eventlistener to handle the exception. http://symfony.com/doc/current/cookbook/service_container/event_listener.html
you need to beat the event dispatcher before it send back an exception, so listen to these kind of events and silence them, though i think this is a BAD way to deal with it
class SuchABadRequest implements \Swift_Events_TransportExceptionListener{
/**
* Invoked as a TransportException is thrown in the Transport system.
*
* #param \Swift_Events_TransportExceptionEvent $evt
*/
public function exceptionThrown(\Swift_Events_TransportExceptionEvent $evt)
{
$evt->cancelBubble();
try{
throw $evt->getException();
}catch(\Swift_TransportException $e){
print_r($e->getMessage());
}
}
}
inside the controller
$mailer = $this->get('mailer');
$mailer->registerPlugin(new SuchABadRequest());
When my Beanstalkd job has an error, like "exception 'ErrorException' with message 'Notice: Undefined index: id in /var/www/mysite/app/libraries/lib.php line 248' in /var/www/mysite/app/libraries/lib.php:248, how should Beanstalkd knows that an error has occured and mark it as failed so it can be retried again?
Install a monitor for beanstalkd which can be useful when developing/testing your app. Some alternatives that uses PHP: http://mnapoli.github.io/phpBeanstalkdAdmin/ and https://github.com/ptrofimov/beanstalk_console
As for handling the errors, you could define your own error handler for beanstalkd jobs and in that handler decide if you want to:
bury (put the job aside for later inspection)
kick (put it back into the queue)
delete (remove it, if this is safe for your application)
EDIT - Did you manage to solve your problem?
The best way might be to use a try/catch around your jobs to catch the exceptions, and then bury it if the exception is raised at the worker. If the exception is raised at the producer it is probably never added into the queue so no need to bury() then, but use a monitor to make sure.
If you want to try to define an own error handler for your object I´ve done something similar before by setting up a custom error handler for your class. It might be a ugly hack by trying to get the pheanstalk (job) object through $errcontext - but might be something to try.. Here is some pseudo-code I quickly put together if you want to try it out (created a subclass to avoid put code into pheanstalk class):
class MyPheanstalk extends Pheanstalk {
function __construct() {
//register your custom error_handler for objects of this class
set_error_handler(array($this, 'myPheanstalk_error_handler'));
//call parent constructor
parent::__construct();
}
function myPheanstalk_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
// get the current job that failed
foreach($errcontext as $val) //print_r($errcontext) to find info on the object(job) you are looking for
{
if(is_object($val)) {
if(get_class($val) == 'Pheanstalk') { //and replace with correct class here
//optionally check errstr to decide if you want to delete() or kick() instead of bury()
$this->bury($val);
}
}
}
}
}
Its your script that has the error, not beanstalkd.
try {
//your code from Line 248 here
} catch (ErrorException $e) { //this section catches the error.
//you can print the error
echo 'An error occurred'. $e->getMessage();
//or do something else like try reporting the ID is bad.
if (!isset($id)) {
echo 'The id was not set!';
}
} //end of try/catch
spl_autoload_register(function ($className)
{
if (file_exists($className . '.php'))
{
require_once($className . '.php');
}
else
{
throw new Exception('Could not load class: ' . $className);
}
});
//Load models and save them in variable instances
try
{
$this->database = new Database (
$config['DB']['HOST_IP'],
$config['DB']['DATABASE_NAME'],
$config['DB']['USERNAME'],
$config['DB']['PASSWORD']
);
//Set the initial language for our template model.
Template::setLanguage();
}
catch (Exception $e)
{
echo $e->getMessage();
}
Script works if I erase file_exists, but file_exists returns false no matter what.
What may be causing this?
Also, I get an error message: Uncaught exception 'Exception' with message 'Could not load class: Template'. Is it because Template class is static?
There are 2 faults with your code.
Instead of meaningful and reasonable system error message you are ecoing just useless and generalized error message which cannot help you
You uare using try-catch just to echo a message. Which is deadly wrong.
So, just get rid of all try-catch blocks in your code and run it again.
And never use try..catch if you're not going to handle an error
instead of that set error reporting to be able to see the error messages
error_reporting(E_ALL);
ini_set('display_errors',1);
The problem was having two extensions on my PHP file. (e.g index.php.php) Sadly, the windows environment wasn't configured so I struggled finding the issue.