Returning error message if function/procedure fails to execute - pascal

In SQL I learned to check for errors in every query that my script executes.
$query = "SELECT * FROM something";
$result=msqli_query($conn, $query);
if(!$result){
echo "There is something wrong with ", $query;
} else {
//Proceed as normal
}
So I figured it might be a good idea to implement the same idea into my pascal program as well. But I don't know how to check for if a part in the program fails to execute or not. I was thinking of something like this
if (//a function/procedure could not execute) then
WriteLn('Error!')
else
//Proceed with other functions/procedures;
In SQL, !$result means mysqli_query returned false because it couldn't execute the query, but I don't know how to do that to pascal functions/procedures...Normally if a function or procedure fails to execute the program will just crash with an error in the terminal, it won't return a false value like in SQL for me to catch and manipulate.

Related

Condition Using Controller in Code Igniter

I'm trying to create a function, it exists and does not exist in the search feature. Condition does not exist, will display Error 404. Condition, exists. Then it will display from search. But in the code I wrote, it only shows Error 404.
This is my model:
function search_album($keyword){
$result=$this->db->query("SELECT tbl_album.*,DATE_FORMAT(album_date,'%d %M %Y') AS date FROM tbl_album WHERE album_title LIKE '%$keyword%'");
return $result;
}
This is my controller:
function search(){
$keyword=str_replace("'", "", $this->input->post('xfilter',TRUE));
$x['data']=$this->model_album->search_album($keyword);
if(empty($x) && empty($keyword)){
$this->load->view('view_contents',$x);
}
else if (!empty($x) && !empty($keyword)){
$this->load->view('view_error_404');
}
}
I've tried from this source, but it doesn't work. Can you help me?
There are several errors in your code:
ONE: You have interchanged your if statements. Like, if the search did not return any data and the keyword was not supplied, it is supposed to display the "view_error_404", otherwise, it is supposed to load data into the view "view_contents".You did the vice versa I have corrected that for you in the code below.
TWO: You are checking if $x is empty which will never be empty as you have initialized $x['data']. Note that the model can return empty data, such that $x['data'] is empty. Instead, check if the search result is empty by replacing empty($x) with empty($x['data'])
THREE: In your model, you are returning the query builder class, but not the actual data from the query statement. instead, replace return $result; with return $result->result();
FOUR:
From your if statements, you need to add an else statement so that if the 2 conditions are never met, it can execute. With your current implementation, there is a state which will not meet first or second conditions and will lead to a blank screen.
if(empty($x['data']) && empty($keyword)){
$this->load->view('view_error_404');
}else if (!empty($x['data']) && !empty($keyword)){
$this->load->view('view_contents',$x);
}else{
$this->load->view('view_error_404'); // replace this code with your preference
}
you need to mention search function in routes.php file like this:-
$routes['search'] ='your_controller_name/search';
without knowing your function model_album->search_album($keyword) and assuming it returns a string or array, you don't need to worry about checking for the keyword, since without a keyword the function should return false or empty.
anyway you mixed up your if/else conditions, since you are checking for not empty results to return a 404, instead of empty result returning the 404.
this should do it:
if(empty($x)){
$this->load->view('view_error_404');
}
else {
$this->load->view('view_contents',$x);
}

Execute a Bash script (Shell Script) from postgres function/procedure/trigger

CREATE or replace FUNCTION test() RETURNS boolean AS $$
$filename = '/home/postgres';
if (-e $filename) {
exec /home/postgres/test.sh &
return true; }
return false;
$$ LANGUAGE plperlu;
exec /home/postgres/test.sh & its showing syntax error.
Could you please help how to call bash script into postgres funtion/procedure
Presumably, the code needs to be syntactically valid Perl. So you'll need to clean up a few bits.
CREATE or replace FUNCTION test() RETURNS boolean AS $$
my $filename = '/home/postgres';
if (-e $filename) {
system '/home/postgres/test.sh' and return 1;
}
return;
$$ LANGUAGE plperlu;
I've changed a few things:
I declare the variable $filename using my
I used system instead of exec. exec replaces the current process - effectively never returning to the calling function
system expects to be passed a string. So I've added quotes around the command
and is usually better in flow control statements than && (and always much better than & which is for bit-flipping, not flow control)
Perl doesn't have true and false, so I've replaced true with 1 (which is a true value in Perl). And I've removed the false from the other return statement - the default behaviour of return is to return a false value
I don't have a Postgresql installation to test this on. If it still doesn't work, please tell us what errors you get.
pl/sh exists, and can be used as a procedual language.
https://github.com/petere/plsh

End a function from a sourced script without exiting script

I have a script with many other scripts sourced. Each script sourced have a function.
One of my function need to stop according to a if statement. I tried continue, break, throw, evrything I saw on internet but either my main script completely end or my function continue.
Function code:
function AutoIndus-DeployUser($path){
$yaml=Get-Content $path | ?{!$_.StartsWith("#")}
$UsersPwd=$false
$user="";$password="";$groups="";$description=""; $options=""
$yaml | %{
if (($_-match "}") -and ($UsersPwd -eq $true)){Write-Host "function should stop"; return}
*actions*
}
}
Main script:
#functions list and link to extern scripts
Get-ChildItem -Path $PSScriptRoot\functions\ | %{$script=$_.Name; . $PSScriptRoot\functions\$script}
myfunction-doesnotwork
*some code*
Edit: I saw that return should stop the function without stoping the rest of the script, unfortunatly it does not stop anything at all:
Output:
Config file found
---
Changing user _usr-dba password
Changing user _usr-dba2 password
function should stop
Changing user _usr-dba3 password
function should stop
function should stop
function should stop
function should stop
function should stop
Disabling user DisableAccounts:{
Disable-LocalUser : User DisableAccounts:{ was not found.
At C:\Scripts\AWL-MS-AUTOMATION_AND_TOOLS\functions\AutoIndus-DisableAccount.ps1:25 char:13
+ Disable-LocalUser -Name $disable
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DisableAccounts:{:String) [Disable-LocalUser], UserNotFoundException
+ FullyQualifiedErrorId : UserNotFound,Microsoft.PowerShell.Commands.DisableLocalUserCommand
Disabling user _usr-dba
To help you understanding, my script read a file and do actions according to each line it is reading. It start acting when it encounter something like User{ and should stop when it encounter }, _usr-dba3 being out of the curvy brackets it should not be treated. This way all my other function use the same one file. (changing user password and diasabling user are two different functions/sourced scripts)
Like you can see return does not do its job, maybe I'm missing one point in the use of return but I don't get it right now.
To prematurely exit out of a function before you reach the end of it, use
return
it works like break to where it will stop execution but instead of stopping the whole thread it will return back to the line below where you called the function.
Also keep in mind if your function has an output set return will return it back, for example with the function below:
function Get-ReturnValue()
{
$returnValue = "this is my output"
return $returnValue
}
if you called it like this:
$receivedReturnValue = Get-ReturnValue
then the variable receivedReturnValue would be loaded with the output of the function.
I needed a fast solution so I changed my functions, now there is no return/continue/... but a value that turn true. It is initialized to false and the action on each yaml lines are done when the value is equal to false.
Edit: So finally the issue was I didn't used function correctly. Return only works if you return into another function. So I putted almost the entire sctipt into a function that calls the function AutoIndus-DeployUser. Now it works perfectly !

dd works but echo does not for an object passed as a parameter to a function in Laravel

I passed an object in a function in laravel.
I tried to assign the value of a property to a variable. It pops an error.
When I tried to figure out what was going on I tried to dd ()the value it worked.
But when I tried to echo the same it does not.
What am I mising.
On using this,
location1 and location2 are two objects of the location class.
The function is here:
function geodistance($location1,$location2){
dd($location1->lat);
$lat1=$location1->lat;
}
it prints
"28.612072"
But when I change the same function to
function geodistance($location1,$location2){
echo($location1->lat);
$lat1=$location1->lat;
}
The output error is:
Trying to get property 'lat' of non-object
Even the function
function geodistance($location1,$location2){
echo $location1->lat;
$lat1=$location1->lat;
}
gives the same output
The aim to remind you is to assign the value to a variable like so.
function geodistance($location1,$location2){
$lat1=$location1->lat;
}
When I echo $location1 from within the function geodistance() gives out and error which makes sense.
function geodistance($location1,$location2){
echo $location1;
$lat1=$location1->lat;
Object of class App\MyClasses\city could not be converted to string
When I dd ($location1 from the funciton like so it gives the right result.
function geodistance($location1,$location2){
dd($location1);
$lat1=$location1->lat;
like so:
city {#13410 ▼
+id: 2245
+info: "{}"
+name: "New Delhi"
+lat: "28.612072"
+lon: "77.22978"
+timezone: null
+weightedrating: null
+country_id: 1
}
It seems i am missing out something very trivial. :(
As pointed out by #salman zafar and #apokryfos, the mistake was that I was passing an array.
When I was doing a dd, after processing the first data the programme was terminated.
The array that was passed was not completely correct. The last data point in my array was not an object of the same class.
So the data ended up being corrupted when using echo. Echo would print one data after another but eventually it would get a wrong input.
The best way to catch these errors (after so much experimenting) is to write the values of the variable in a text file on each iterartion.
What that does is that it catches the error in your text file and u get to know after how many iterations the programme stopped.
Hope this helps others from making such obviously glaring mistakes which are tough to catch (atleast for me since this was the first of such errors)

Print debug messages to console from a PowerShell function that returns

Is there a way to print debug messages to the console from a PowerShell function that returns a value?
Example:
function A
{
$output = 0
# Start of awesome algorithm
WriteDebug # Magic function that prints debug messages to the console
#...
# End of awesome algorithm
return $output
}
# Script body
$result = A
Write-Output "Result=" $result
Is there a PowerShell function that fits this description?
I'm aware of Write-Output and Write-*, but in all my tests using any of those functions inside a function like the one above will not write any debug messages. I'm also aware that just calling the function without using the returned value will indeed cause the function to write debug messages.
Sure, use the Write-Debug cmdlet to do so. Note that by default you will not see debug output. In order to see the debug output, set $DebugPreference to Continue (instead of SilentlyContinue). For simple functions I will usually do something like this:
function A ([switch]$Debug) {
if ($Debug) { $DebugPreference = 'Continue' }
Write-Debug "Debug message about something"
# Generate output
"Output something from function"
}
Note that I would not recommend using the form return $output. Functions output anything that isn't captured by a variable, redirected to a file (or Out-Null) or cast to [void]. If you need to return early from a function then by all means use return.
For advanced functions you can get debug functionality a bit more easily because PowerShell provides the ubiquitous parameters for you, including -Debug:
function A {
[CmdletBinding()]
param()
End {
$pscmdlet.WriteDebug("Debug message")
"Output something from cmdlet"
}
}
FYI, it's the [CmdletBinding()] attribute on the param() statement is what makes this an advanced function.
Also don't forget about Write-Verbose and $pscmdlet.WriteVerbose() if you just want a way to output additional information that isn't debug related.

Resources