CakePHP 2.0 - customize database error message - database

I have a CakePHP 2.0 application with a MySQL database. Two database tables are connected with a 1:n relation and a foreign key constraint.
So if I want to delete an entry which is connected in the other database table, I get the error:
Error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a forein key constraint fails (...)
SQL Query: DELETE 'Test' FROM 'tests' AS 'Test' WHERE 'Test'.'id' = 10
Notice: If you want to customize this error message, create app/View/Errors/pdo_error.ctp
But what I want to do is to handle the error message! I read something about 'onError' but putting it into the 'AppModel' it seems not to be called (maybe it works only with CakePHP 1.3?):
class Test extends AppModel {
function onError() {
echo "TESTTESTTEST";
$db = ConnectionManager::getDataSource('default');
$err = $db->lastError();
$this->log($err);
$this->log($this->data);
}
}
So what can I do? I want to remain on this page, and I want to show only an error message (not a stack trace and this kind of stuff).
Anyone an idea?

What about using the .ctp?
If you want to customize this error message, create app/View/Errors/pdo_error.ctp
The one that's being used is in the Cake directory, you could just copy that to your app/View/Errors directory and remove the stack trace from that if you like.
There's also the beforeDelete() Model callback function you could use to set a flashMessage.

Data base error normally give 500 error so cakephp handle 500 exception by using
View/Errors/error500.ctp or app/View/Errors/pdo_error.ctp only and customize this page
and add this function bellow in AppController.php
function beforeRender() {
if($this->name == 'CakeError') {
$this->set('title','Internal error occurs');
$this->layout = 'frontend';
}
}

Related

Laravel 8 Fortify User UUID Login Problem

I am currently setting up a new project using Laravel 8. Out of the box, Laravel is configured to use auto-incrementing ID's for the user's ID. In the past I have overrode this by doing the following.
Updating the ID column in the user table creation migration to
$table->uuid('id');
$table->primary('id');
Adding the following trait
trait UsesUUID
{
protected static function bootUsesUUID()
{
static::creating(function ($model) {
$model->{$model->getKeyName()} = (string) Str::orderedUuid();
});
}
}
Adding the following to the user model file
use UsesUUID;
public $incrementing = false;
protected $primaryKey = 'id';
protected $keyType = 'uuid';
On this new project, I did the same as above. This seems to break the login functionality. When the email and password are entered and submitted, the form clears as though the page has been refreshed. Thing to note is there are no typical validation error messages returned as would be expected if the email and/or password is wrong.
To check that the right account is actually being found and the password is being checked properly, I added the following code to the FortifyServiceProvider boot method. The log file confirms that the user is found and the user object dump is correct too.
Fortify::authenticateUsing(function(Request $request) {
\Log::debug('running login flow...');
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
\Log::debug('user found');
\Log::debug($user);
return $user;
}
\Log::debug('user not found');
return false;
});
Undoing the above changes to the user model fixes the login problem. However, it introduces a new problem that is the login will be successful but it wont be the right account that is logged in. For example, there are 3 accounts, I enter the credentials for the second or third account, but no matter what, the system will always login using the first account.
Anyone have any suggestions or ideas as to what I may be doing wrong, or if anyone has come across the same/similar issue and how you went about resolving it?
Thanks.
After digging around some more, I have found the solution.
Laravel 8 now stores sessions inside the sessions table in the database. The sessions table has got a user_id column that is a foreign key to the id column in the users table.
Looking at the migration file for the sessions table, I found that I had forgot to change the following the problem.
From
$table->foreignId('user_id')->nullable()->index();
To
$table->foreignUuid('user_id')->nullable()->index();
This is because Laravel 8 by default uses auto incrementing ID for user ID. Since I had modified the ID column to the users table to UUID, I had forgotten to update the reference in the sessions table too.

Laravel 5.2 - method DELETE not allowed (error 405)

I have a database with two tables: table CATEGORIES has an id that is the fk of table PRODUCTS.
When I want to delete a category, and a record in table products has associated that category id, laravel return a 405 error and i cannot access to destroy method. How can I avoid 405 error and access to destroy method?
Here's my route config:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1',['middleware' => ['api']], function($api){
$api->resource('categories', 'App\Http\Controllers\CategoriesController');
$api->resource('products', 'App\Http\Controllers\ProductsController');
$api->get('categories/{id}/products', 'App\Http\Controllers\CategoriesController#products');
});
EDIT
If the category isn't associated with any product, delete method doesn't throw any error so I guess it isn't a route problem
Laravel only returns HTTP 405 if a route exists but not for that method. I'm not entirely familiar with Dingo, but run php artisan route:list to check that the route you're trying to use has been registered for a DELETE request.

cakephp - How to handle integrity constraint violation errors

Am at a loss here. I need to know how to handle error messages in case of integrity constraint violations.
Meaning i want to show users some meaningful message instead displaying error messages like
Error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
I need to capture these databse errors and just show messages like say
The item you are trying to delete is associated with other records
How do we deal with this.
i have found a refernce here : https://stackoverflow.com/a/8842963/576523
but i dont want to do a count check.
When we use the debug_kit plugin we can see that they have captured these values under the
variables tab. I need a way to do this or access these data from the debug_kit plugin.
Thankz.
You could also use try - catch
try {
$this->Item->delete();
} catch (Exception $e) {
$error = 'The item you are trying to delete is associated with other records';
// The exact error message is $e->getMessage();
$this->set('error', $error);
}
If you only want to catch a specific exception, specify the exception class in the catch block.Hope it will solve your problem.
try {
$this->Item->delete();
} catch (\PDOException $e) {
$error = 'The item you are trying to delete is associated with other records';
//exact error message $e->getMessage();
}
Using CAKEPHP3 -> CakePHP 3 - Catch Error
try
{}
catch (\PDOException $e)
{}
Solved like a charm ;) - \Exception or \PDOException

Windows Azure The remote server returned an error: (404) Not Found

I'm following this tutorial which is about Table Storage Service. I'm using the emulator version of the tutorial which you can find at point 5 of paragraph "Configuring your connection string when using Cloud Services".
This is the code I pasted in the 'About' ActionResult:
public ActionResult About()
{
// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");
// Create a new customer entity.
CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
customer1.Email = "Walter#contoso.com";
customer1.PhoneNumber = "425-555-0101";
// Create the TableOperation that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(customer1);
// Execute the insert operation.
table.Execute(insertOperation);
return View();
}
At this line table.Execute(insertOperation); I get the following error message:
StorageException was unhandled by user code The remote server returned
an error: (404) Not Found.
The project template I used was "Windows Azure Cloud Service". The next window that popped up, I only added "ASP.NET MVC 4 Web Role".
Anyone any idea what is causing this error?
Does the people table exists in Storage area? (you can check from Azure management portal)
I came here after getting the same error(Not found when .replace), but my case was different, I actually had people table but the problem with my code is that I was updating the Row key value.
I think you can only update the other fields but not the partition keys or the row keys. Just thought of adding this to the answers in case someone else gets the same issue as me.

atk4 SQLAuth in Frontend.php

in Frontend.php I replaced this:
$this->add('BasicAuth')
->allow('demo','demo')
// use check() and allowPage for white-list based auth checking
//->check()
;
With this:
$this->add('SQLAuth')->setSource('user','email','password')
// use check() and allowPage for white-list based auth checking
//->check()
;
based on this you tube video: http://www.youtube.com/watch?v=0_OROS53Fq8&feature=relmfu
However, the SQLAuth will not work. I get this error:
Fatal error: Call to a member function loaded() on a non-object in
C:\wamp\www\atk4\lib\Auth\Basic.php on line 242
My table name is correct, and i know the connection is working and there are users in the table, because I built a user registration form and CRUD that works as I walked through the you tube video.
Anybody have an idea what I am doing wrong here?
SQLAuth is going to be removed in 4.2 and should not be used anymore. You can use BasicAuth and set it to respond to a model based on your user table

Resources