exception tracking and blocking it in zend framework 2 - exception

How to stop exception from showing in zend framework 2 and instead when exception is thrown i want to redirect to 404 page .
Actually when user fires wrong url or some how any query gets executed in a wrong way exception is thrown , so i need to block this exception and instead redirect to any other well designed page . I'm unable to track the the exception point or rather catch the exception or from where exception is generated . I have used this code
You can handle the exceptions in anyway you want after catching it as the following example in which you are catching the exception globally...:
In the onBootstrap method i have attached the following code in Module.php in a function to execute when an event occurs, the following attach a function to be executed when an error (exception) is raised:
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$em = $application->getEventManager();
//handle the dispatch error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, array($this,
'handleError'));
//handle the view render error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER_ERROR, array($this,
'handleError'));
}
and then defineed in module.php only the function to handle the error
public function handleError(MvcEvent $e)
{
//get the exception
$exception = $e->getParam('exception');
//...handle the exception... maybe log it and redirect to another page,
//or send an email that an exception occurred...
}
I found this code from stackoverflow only , but it is not working , i mean when i'm passing wrong parameters in url , it is showing " A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
Front\Controller\Front
No Exception available "
Please i need help on this.

you can turn off exceptions in zf2 by chaining 'display_exceptions' => TRUE to 'display_exceptions' => false, [module/Application/config/module.config.php]

Related

Exception details in ABP framework

I wanna return the details of exception with ABP .NET Core, what I noticed is when I go to AbpAuditLogs table and App_Data\Logs logFile they contain the exception in details but when I use below method to return the exception it shows only general exception without any details (500 Internal Server Error)
try{
:
:
:
}
catch (Exception ex)
{
throw new System.ArgumentException(ex.InnerException.Message.ToString(), "original");
}
So, How could I return the specific Exception for the user for Example Email Validation Exception and so on?
Update:
I will explain more to make the question more clear :
The way that I handled the exception is attached with this question above .
The problem is when hitting a request on the service from swagger or Postman always see General Error with status Code 500 without any details and that force me to review the details of the exception from Log File or Log Table , I wanna see the details of the exception (e.g FileNotFoundException ) directly from Swagger or Postman without return back to Log File or AbpAuditLogs Table.
I think User Friendly Exception will work for you.
Because if an exception implements the IUserFriendlyException interface, then ABP does not change it's Message and Details properties and directly send it to the client.
throw new UserFriendlyException(
"Username should be unique!"
);
You can find more information here.
Actually, I found the answer in this question for #Mehdi Daustany .what I did is exactly what #Mehdi Daustany answered, I've added below code :
if (_env.EnvironmentName.ToLower() == "development")
Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;
under ***.Web.Core then the details of exception appeared in the Swagger
services.Configure<AbpExceptionHandlingOptions> (options =>
{
options.SendExceptionsDetailsToClients = true;
});
Above code will configure abp to return all the exception details. Just add it to the configuration.

Silex : log dbal exceptions

I'm using Silex micro-framework. I searched a method to log every dbal exceptions (from requests, console commands, etc...)
I didn't find something which works. Even if I declare a callback function in $app->error();, it doesn't works to Console exceptions
How can I tell to dbal to log in a file all db errors/exceptions ?
If you have the fat version of Silex you should already have exception logging with MonologServiceProvider, as long as it has been registered.
The console is usually an instance of Symfony\Component\Console\Application (not Silex\Application).
Edit One way to accomplish logging console exceptions is to set console catch exceptions to false:
$console->setCatchExceptions(false);
And then wrap $console->run(); in a try catch:
try {
$console->run();
}
catch(\Doctrine\DBAL\DBALException $e) {
$app['monolog']->addError(sprintf('Console DBALException %s %s %s', $e->getMessage(), $e->getTraceAsString(), $e->getFile(), $e->getLine()));
}
catch(\Exception $e) {
$app['monolog']->addError(sprintf('Console Exception %s %s %s', $e->getMessage(), $e->getTraceAsString(), $e->getFile(), $e->getLine()));
}

Typo3 scheduler handling exceptions?

I'm currently programming a scheduler task to run in my typo3 backend. For more security and a better debuggable workflow I want to throw exceptions that get displayed in the "scheduled tasks" section when running a task as well as display a red box rather than a green box because the task has failed. Unfortunately I cant get it work. Returning an exception ends in a printed exception-string with a green/success infobox. When just throw the exception by throw new Exception ends in a red/error infobox with no hint what the exception message was.
public function importCommand($filetype) {
try {
if(!$this->isValidFileTypeConfigured($filetype)) {
throw new \TYPO3\MbxRealestate\Helper\Exception\ImportImmoException('Unsupported filetype "' . $filetype . '" configured in ' . __CLASS__ . '::' . __FUNCTION__);
}
....
} catch (\Exception $ex) {
throw $ex; // throwing ...
return $ex; // or returning
}
return true;
}
You can use the Flash Message API in TYPO3 to output your errors. There are 5 types of errors and respective styling. See here:
http://docs.typo3.org/TYPO3/CoreApiReference/ApiOverview/FlashMessages/Index.html

Grails error handler always receives null pointer

We have a custom error controller that gets called after all of our errors. However, most of our errors that get thrown end up coming into the controller as null pointers, even though the original error was not a null pointer. Any ideas? Code below. Bootstrap and UrlMappings available if needed. Thanks
Error Handler method
def HandleErrors =
{
def exception = request.exception.cause.class
if (exception)
{
Exception ex = request.exception //This exception is always a NPE
...
Block of code throwing the exception. I originally did not have a try catch in here, but wanted to add it so that I was sure the exception being thrown was Not a NPE. Its a file not found exception.
try{
def writer = new FileWriter( new File(fileSaveLocation));
}
catch ( ex)
{
throw(ex)
}
Edit: Adding the exception that is pushed to the exception handler
Exception:org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException
Cause:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
It's not because you're referencing something that is null inside the error handler, and so are inadvertently throwing another exception, which is again caught?
can you try changing:
def exception = request.exception.cause.class
to
def exception = request?.exception?.cause?.class

Zend AMF and exception handling

I have created an Zend AMF service using the FlashBuilder tools. What I wanted to try was to change one of those automatically created methods to throw an exception in order to see the behaviour. Instead of the exception being serialized back to my Flex app it gives me the following:
[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:345]
at mx.rpc::Responder/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\Responder.as:68]
at mx.rpc::AsyncRequest/fault()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:113]
at NetConnectionMessageResponder/channelDisconnectHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:684]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.messaging::Channel/disconnectSuccess()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\Channel.as:1214]
at mx.messaging.channels::NetConnectionChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\NetConnectionChannel.as:175]
at mx.messaging.channels::AMFChannel/internalDisconnect()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:355]
at mx.messaging.channels::AMFChannel/statusHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\messaging\channels\AMFChannel.as:445]
The channel disconnects...
[RPC Fault faultString="Channel disconnected" faultCode="Client.Error.DeliveryInDoubt" faultDetail="Channel disconnected before an acknowledgement was received"]
This is the code:
public function getAllUser() {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);
while (mysqli_stmt_fetch($stmt)) {
$row->created_on = new DateTime($row->created_on);
$row->modified_on = new DateTime($row->modified_on);
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->id, $row->user_group_id, $row->username, $row->password, $row->active, $row->activation_key, $row->timezone, $row->created_on, $row->modified_on);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
$errorCode = 1;
throw(new Exception('the error message you want', $errorCode));
return $rows;
}
Notice the throw statement:
throw(new Exception('the error message you want', $errorCode));
I really didn't expect this. How can I make it work?
Thank you in advanced!!!
Zend Amf is just a serialization protocol of response types to cast them into the AMF format. No error messages are sent back as they normally have sensitive security information in them. Most other PHP amf serialization do not work this way. If you have an exception you need to catch it and convert it to a standard support response type. Also in any of your code every Try needs a Catch as it is not a control structure even if PHP allows you to get away with it.
If you have configured your endpoint to not be production and just need it for debugging.
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('the error message you want', $errorCode);
Well it does serialize the exception message and code which does the job for us. Partially but does it. I didn't notice that the service component I copied the code from in my question contained an exception handler which would suppress the exception and just disconnect the channel. I removed the exception handler letting the exception bubble up to Zend which in turn send the exception message and message code to the client.
I would like to have the actual exception sent as an AS3 object but what can I say. In this way I would have the properties of the exception serialized also. Unfortunately the same goes for custom exceptions.