Exception handling issue in zend framework 2 - exception

try {
Zend_Loader::loadClass('nonexistantclass');
} catch (Zend_Exception $e) {
echo "Caught exception: " . get_class($e) . "\n";
echo "Message: " . $e->getMessage() . "\n";
}
I'm using your above code for zend framework 2 in some controller action method , after executing some line its getting blank , It seems that exception has been caused but why the its not displaying $e->getMessage() content . Do i need to use any name space for using this , or what is the correct way to use Exception Handling in zend framework 2 . Please help me

Just trying to provide a sample code.
It should be -
try {
$model = new NonExistantClass(); //Any code that will throw an Exception.
} catch (\Exception $e) {
echo "Message: " . $e->getMessage();
}
The \ backslash before the Exception $e states that the Class is not under the namespace mentioned at the top of the page but its the core PHP class.

Related

HTTP request doesn't get Json expression with values contain a dot "."

I have a Json expression that contains values with "." and # like this
{"queued":"C1F","messageid":"dfs.jfdsf#sdf.abc.fr"}
that doesn't get processed by HTTP POST request , and it's give me this result :
"code":400,"message":"Unable to process JSON
PS: my web server is created with dropWizard in Intellij IDEA
how can I resolve this problem
EDIT: this is the code used in perl
my $queued=$1; my $messageid=$2 ;
my $json= "{\"queued\":\"$queued\",\"messageid\":\"$messageid\"}";
$req1->content($json);
my $response=$ua->request($req1);
if ($response->is_success) {
my $message =$response->decoded_content ;
print "resultat : $message \n";
}
else {
print "erreur", $response->code, " ", $response->message, "\n" ;
}
It would be less error-prone to use the JSON library to build your JSON string
use JSON 'to_json';
my $json = to_json({ queued => $queued, messageid => $messageid });

Parsing JSON In Perl

I'm trying to parse JSON data in Perl. it is request to Cisco Prime Service. My script works, but parsing doesn't work. And I have a warning,
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "HTTP::Response=HASH(...") at InternetBSP.pl line 39.
It is here:
my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($res);
have no Idee how should I fix it...
use strict;
use warnings;
use JSON -support_by_pp;
use LWP 5.64;
use LWP::UserAgent;
use MIME::Base64;
use REST::Client;
use IO::Socket::SSL;
#So dass es auch ohne SSL Sertifizierung funktioniert
BEGIN { $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0 }
#Create a user agent object
my $ua = LWP::UserAgent->new(
ssl_opts => {
SSL_verify_mode => SSL_VERIFY_NONE(),
verify_hostname => 0,
}
);
#Create a request
my $req = HTTP::Request->new( GET => 'https://10.10.10.10/webacs/api/v1/data/AccessPoints.json?.full=true' );
$req->content_type('application/json');
$req->authorization_basic( "Username", "Password" );
#Pass request to the user agent and get a response back
my $res = $ua->request($req);
#Check the outcome of the Response
if ( $res->is_success ) {
print $res->content;
} else {
print $res->status_line, "n";
}
my $json = new JSON;
my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($res);
#my try to pasre the data
foreach my $ap ( #{ $json_text->{queryResponse}->{'entity'} } ) {
print "------------------------\nAccess Point " . $ap->{'accessPointsDTO'}->{'#id'} . "\n";
print "Model:" . $ap->{'accessPointsDTO'}->{'model'} . "\n";
print "MAC Address:" . $ap->{'accessPointsDTO'}->{'macAddress'} . "\n";
print "Serial Number:" . $ap->{'accessPointsDTO'}->{'serialNumber'} . "\n";
print "Software Version:" . $ap->{'accessPointsDTO'}->{'softwareVersion'} . "\n";
print "Status:" . $ap->{'accessPointsDTO'}->{'status'} . "\n";
print "Location:" . $ap->{'accessPointsDTO'}->{'location'} . "\n";
}
I have this like outcome:
{"queryResponse":{"#last":"7","#first":"0","#count":"8","#type":"AccessPoints","#responseType":"listEntityInstances","#requestUrl":"https:\/\/10.66.1.23\/webacs\/api\/v1\/ data\/AccessPoints?.full=true","#rootUrl":"https:\/\/10.66.1.23\/webacs\/api\/v1\/data","entity":[{"#dtoType":"accessPointsDTO","#type":"AccessPoints","#url":"https:\/\/10 .66.1.23\/webacs\/api\/v1\/data\/AccessPoints\/205320"
But it shoud be smth like:
{"queryResponse":
{"#type":"AccessPoints",
"#rootUrl":"https://172.18.138.90/webacs/api/v1/data",
"#requestUrl":"https://172.18.138.90/webacs/api/v1/data/AccessPoints?.full=true",
"#responseType":"listEntityInstances",
"entity":[
{"#url":"https://172.18.138.90/webacs/api/v1/data/AccessPoints/13544533",
"#type":"AccessPoints",
"#dtoType":"accessPointsDTO",
"accessPointsDTO":
{"#id":"13544533",
"#displayName":"13544533",
"adminStatus":"ENABLE",
"bootVersion":"12.4.23.0",
"clientCount":0,
After update :)
------------------------
Access Point 205320
Model:AIR-LAP1142N-E-K9
MAC Address:6c:9c:ed:b5:45:60
Serial Number:FCZ1544W51B
Software Version:7.6.130.0
Status:CLEARED
Location:de.bw.stu.
------------------------
Access Point 205322
Model:AIR-CAP3502I-E-K9
MAC Address:0c:f5:a4:ee:70:10
Serial Number:FCZ184680VB
Software Version:7.6.130.0
Status:CLEARED
Location:de.bw.stu.
------------------------
Access Point 205324
Model:AIR-LAP1142N-E-K9
MAC Address:6c:9c:ed:86:9d:20
Serial Number:FCZ1544W50Y
Software Version:7.6.130.0
Status:CLEARED
Location:de.bw.stu.
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "HTTP::Response=HASH(...")
This error message means that the data you are giving to decode is not JSON.
You are passing $res to decode, which is an HTTP::Response object (see above, emphasis mine). You need to use $res->content, which you use for debugging output a few lines above.
if ($res->is_success) {
print $res->content;
} else {print $res->status_line, "n";
}
I would rewrite that whole block of code to this.
die $res->status_line unless $res->is_success;
my $json = JSON->new->allow_nonref
->utf8->relaxed
->escape_slash->loose
->allow_singlequote->allow_barekey;
my $json_text = $json->decode( $res->content );
Instead of printing some debug output and then going on anyway if things went wrong you can just die if the request was not successful.
After that, create your JSON object and configure it. This is way more readable than this long line of code, and we're using a method call to new instead of indirect object notation.
Finally, we are decodeing $res->content.

MySql (popup message box if failed to insert data)

Hi I have a code that print out some message if the data are successfully inserted into database.
This is the code:
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record saved!";
How do I make it so that instead of opening a new page and print them, I need them to just display a message box indicating whether it is successful or not.
Thank you.
Try this:
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
echo '<script language="javascript">';
echo 'alert("Record saving failed")';
echo '</script>';
}else{
echo '<script language="javascript">';
echo 'alert("Record saved")';
echo '</script>';
}
if (!mysql_query($sql,$con)){
echo "<script type='text/javascript'>alert('failed!')</script>";
}else{
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
}
Use this to get a message box.

Uncatchable Exception (PowerShell)

I have code that reliably generates an exception. This is expected so I don't want it to show up at the end of my script when I dump the $error variable to look for actual problems.
Well step 1 is to find this exception and handle it, right? I can't get that far. Here is what I've got:
Function Add-PowerShellSnapIn($SnapInName){
Try{
if ((Get-PSSnapin -Name $SnapInName) -eq $null){
Write-Warning "SnapIn Is Not Already Loaded"
}
}Catch [System.Exception]{
Write-Warning "Error Caught"
}
}
Add-PowerShellSnapIn -SnapInName "Microsoft.Exchange.Management.PowerShell.Admin"
If I run this code I can see the exception, but I never see my little "Write-Warning" test message to indicate that the Catch block caught the exception. I must be missing something here. Here is the exception I see:
Get-PSSnapin : No Windows PowerShell snap-ins matching the pattern 'Microsoft.Exchange.Management.PowerShell.Admin' were found. Check the pattern and then try the command again.
At C:\users\myuser\Desktop\Test.ps1:4 char:20
+ if ((Get-PSSnapin <<<< -Name $SnapInName) -eq $null){
+ CategoryInfo : InvalidArgument: (Microsoft.Excha...owerShell.Admin:String) [Get-PSSnapin], PSArgumentException
+ FullyQualifiedErrorId : NoPSSnapInsFound,Microsoft.PowerShell.Commands.GetPSSnapinCommand
Edit: Thanks in advance for anyone who takes the time to help me out!
You should add -ErrorAction stop to your Get-PSSnapin to get into the Catch Block.
Function Add-PowerShellSnapIn($SnapInName){
Try{
if ((Get-PSSnapin -Name $SnapInName -ErrorAction Stop) -eq $null){
Write-Warning "SnapIn Is Not Already Loaded"
}
}Catch [System.Exception]{
Write-Warning "Error Caught"
}
}
Add-PowerShellSnapIn -SnapInName "Microsoft.Exchange.Management.PowerShell.Admin"

zend framework 2 how catching exceptions?

How I can catch exception in zend framework 2 using the PHP base Exception?
If line is uncommented then Exception class not found and exception is uncatched.
If line is commented the namespace is null and PHP base Exception class is founded.
I can't uncommented this line because is required by zend in many places, i.g. ActionController.
How do it?
Have I to use only Zend Exceptions?
which I have to use and what is the more generic zend Exception class?
<?php namespace SecureDraw; ?> // <<----- If remove this line catch work ok!!
<?php echo $this->doctype(); ?>
<?php
use Zend\Db\Adapter\Adapter as DbAdapter;
try{
$dbAdapter = new DbAdapter(array(
'driver' => 'Pdo_Mysql',
'database' => 'securedraw',
'username' => 'root',
'password' => '',
));
$sql = "select * from tablenotexist";
$statement = $dbAdapter->createStatement($sql);
$sqlResult = $statement->execute();
}
catch(Exception $e){
echo "hello";
}
?>
You need to either add:
use Exception;
or use:
catch (\Exception $e) {
All the built in PHP classes exist within the root (\) namespace. The try-catch in your example is trying to match SecureDraw\Exception.
This is the same issue as How to catch exceptions in your ZF2 controllers?