Laravel not running try catch block - php

Ive run into a little issue.
Im calling a method using the following
$this->testConnection($request->all());
The method looks like so
private function testConnection($data)
{
try {
$conn = ftp_connect($data['host']);
if (false === $conn) {
throw new Exception('Cant connect');
}
} catch (\Exception $e) {
return redirect()->route('create')->withInput()->withErrors($e->getMessage());
}
}
Update: It seems the ftp_connect PHP function isn't working and its not returning any errors
Im using Laravel 5.3
Any help would be grand.
Cheers,

The solution to this was that i was missing
use Exception;

Related

PHP Correct way to call mysqli using Intelephense

This code triggers my editor's intelephense for error:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name']);
} catch (\exception $e) {
throw new \exception($e->getMessage(), $e->getCode());
}
}
Expected 6 arguments. Found 4.intelephense(10005)
would it be fine if I just use:
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'],null,null);
Thank you all for answering; also deceze who corrected me on wrong way to catch exception;
this is edited code:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'], ini_get('mysqli.default_port'), ini_get('mysqli.default_socket'));
} catch (\exception $e) {
echo 'Cannot connect to a database server'; die();
}
}
note ,this is for withing the class using namespaces...
The intelephense plugin uses the stubs from PhpStorm. The author already submitted a PR to fix this (and other functions with optional parameters): https://github.com/JetBrains/phpstorm-stubs/pull/520.
As soon as that's merged and the stubs are updated, you should no longer receive the problem reported in vscode.
There should be no need to change your constructor call, it is valid code and will execute without problems.

PHP throws an exception in subroutine stops working

I have a custom class with function, which calls a function of the Yii2 core BasisAuthentication. In the core module is defined, if the credentials are not valid,
throw new UnauthorizedHttpException('Your request was made with invalid credentials.');
With this, the whole request is ended. But I need to go further (because it is a REST request).
I've tried to prevent from that with
try {
$identity = $basic_Auth->authenticate($user, $request, null );
} catch (Exception $e) {
return null;
}
But this is not working. I don't want to adapt the core files of Yii. What can I do?
try {
$identity = $basic_Auth->authenticate($user, $request, null );
} catch (\Throwable $e) {
return null;
}

Why isn't my catch block not works while passing LINUX command in email?

I have some code that looks like this
try
{
$emailObj->checkEmailExist($emailid);
}
catch(Exception $e)
{
echo 'Insert Record.';
$emailObj->addEmail($emailid);
}
static function checkEmailExist($emailID)
{
$rowset = $this->_tableGateway->select(array('user_email_id'=>$emailID));
$row = $rowset->current();
}
if (!$row) {
throw new \Exception("Could not find data for email : $emailID",404);
}
return $row;
}
now when i passing email that contains any LINUX commands like scp, rcp, ssh then catch block not executed
if i passed email like
test#gmail.com
it check if exist or not, if not then insert email
if I passed email like
ssh.test#gmail.com
it stops execution with throw an exception, even email not exist -
Insert function not executed.
I am not sure why catch block not getting worked with LINUX commands in email?
Please help...
I think probably your class is namespaced, if so you need to root out the Exception class you are catching for:
try
{
$emailObj->checkEmailExist($emailid);
}
catch(\Exception $e)
{
echo 'Insert Record.';
$emailObj->addEmail($emailid);
}
By adding \ in front of it, or it looks for namespace\Exception by default.
I'm just guessing that based on how you throw the exception
throw new \Exception("Could not find data for email : $emailID",404);
You wouldn't need to use \Exception if your class wasn't namespaced. You could do Exception instead.
Cheers!
One last thing, the code you put is totally invalid:
try{
...
}
static function checkEmailExist(){
...
}
To me this says:
<?php
namespace somename;
class someclass{
try{
...
}
static function checkEmailExist(){
...
}
}
In which place you cant put that try block there. But maybe it's not really like that and what you posted is a simplification?

Using Exceptions to control application flow

I am currently writing a web app in PHP and have decided to use exceptions (duh!).
I could not find an answer to whether putting try and catch blocks in all functions would be considered bad code.
I am currently using Exceptions to handle Database errors (Application errors are handled via a simple function which just adds them to an array and then they are displayed to the user). The try blocks are placed on all functions which require a database connection.
The code in question is:
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
And an example function using this code:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
Also would it be better to extend the Exception class and then use that new Exception class to handle application errors?
Thanks
I suggest to you to use something like this:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
I prefer to use my exends of Exception, but is the same. For exdending exception you can see the PHP documentation to Example #5
EDIT: For an immediate use of try-catch on database connection error you can try this:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}

How can I check if file exists with exception handeling

I am trying to use exception handling in case a file does not exists. For example when I run the model method and pass a string usr (which I know there is no file with that name) . It gives me the following error message
Fatal error: Uncaught exception 'Exception' with message 'Usr.php was not found' in /app/core/controller.php on line 14
I can't figure out whats wrong here. Can someone please help me figure this out?
Below is my code. Thanks alot!
class Controllers{
public function model($model){
if(!file_exists("../app/models/".$model.".php")) {
throw new exception("{$model}.php was not found");
}
try {
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
You can't throw an exception without catching it; this automatically causes the PHP script to crash. So, you need to surround your entire function in the try-catch block, or the "model not found" exception will be uncaught. Your code should be something like this:
<?php
class Controllers {
public function model($model){
try {
if (!file_exists("../app/models/".$model.".php")) {
throw new Exception("{$model}.php was not found");
}
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
Never mind guys! I found out I needed to use the try/catch blocks in the file where my method is being invoked
Example..
class Home extends Controllers{
public function index($name = ""){
try{
$user = $this->model('Usr');
}catch (Exception $e){
echo $e->getMessage();
}
//var_dump($user);
}

Categories