cakephp - How to handle integrity constraint violation errors - cakephp

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

Related

How to create custom error page in salesforce

If any error occurred in salesforce site it show line number with class name (please refer below image) which we don't want to show to user.
Instead I want to display custom page in which details like class name, line number will be saved in object or send it via email to developer.
For security reason we want to hide details from user. Even I did not found any option In Site-> "Error Pages" to add custom page for apex error.
You can have a try catch block for your code where you think exception can occur.
For getting stack trace of the error log with class name and line number's we have a method called getStackTraceString().This method returns the stack trace of the error as a string.
Example:
try {
Merchandise__c m = [
SELECT Name
, Total_Inventory__c
FROM Merchandise__c
LIMIT 1
];
Double inventory = m.Total_Inventory__c;
} catch(Exception e) {
System.debug('Exception type caught: ' + e.getTypeName());
System.debug('Message: ' + e.getMessage());
System.debug('Cause: ' + e.getCause()); // returns null
System.debug('Line number: ' + e.getLineNumber());
System.debug('Stack trace: ' + e.getStackTraceString());
}
Please refer this link to view other Exception Methods which will help for tracing your error
Let me know if you need more help. Thanks :)

How to validate a related entity still exists in database, on form submit?

I have an entity Activity, with a CRUD in one part of my app.
In another part of the app, I have a form representing a UserData entity, with a #ManyToOne relation to Activity.
When submitting this form, I want to validate that chosen Activity still exists in database (because of CRUD, it could be deleted between the form loading and the form submit).
I dug a lot into symfony core files, and found that this validation is done the Form component, in viewToNorm() method which throw a TransformationFailedException, which is then silenced by the submit() method :
public function submit($submittedData, $clearMissing = true)
{
try {
[...]
// Normalize data to unified representation
$normData = $this->viewToNorm($viewData);
[...]
} catch (TransformationFailedException $e) {
$this->transformationFailure = $e;
// If $viewData was not yet set, set it to $submittedData so that
// the erroneous data is accessible on the form.
// Forms that inherit data never set any data, because the getters
// forward to the parent form's getters anyway.
if (null === $viewData && !$this->config->getInheritData()) {
$viewData = $submittedData;
}
}
}
I tried to build a custom Constraint with a custom Validator, but it doesn't work, because in case of Transformation failure, Symfony reset the data to it's original form value, so my validator receive a NULL value instead of the deleted entity.
I could build a DataTransformer and catch this exception manually, but DataTransformer are not meant to perform validation.
Is there any other way to check a relation still exists in database and at the end, customize the message displayed in FormError ?

cakephp email object notify on failure

I have this code in my cakephp 2 installation to send out emails
if($Email->template('invitation', 'default')
->emailFormat('html')
->from(array('no-reply#domain.com' => 'MyHospitals'))
->to($email)
->subject($subject)
->send()){
This works fine as long as smtp settings and everything is fine. However if someone changes the password, this fails miserably ....is there a check I can add that will tell me that $Email object was formatted correctly so that if it was not, I can kill it gracefully instead of having errors showing up on the page
thanks
try {
if ($Email->template('invitation', 'default')
->emailFormat('html')
->from(array('no-reply#domain.com' => 'MyHospitals'))
->to($email)
->subject($subject)
->send()) {
// Do success stuff
} else {
// Handle failure (no exception thrown)
}
} catch (Exception $e) {
// Handle exceptions
}

CakePHP 2.0 - customize database error message

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';
}
}

Trigger a 404 error with CakePHP 2.0?

I've been reading CakePHP's 2.0 migration guide where it's stated that cakeError() has been removed because it was used for exceptions. It's a really weird change IMHO because I used it to block access to unauthorized users or to trigger an error when the paginated items exceeded the total, and things like that.
And now what? Should I just throw a die() or a redirect? I really want to let know the users that something was not found and Cake used to provie a stright way to do so... now it doesn't.
Any thoughts/hacks/workarounds about it? Thanks, happy holidays!
You have to throw the corresponding exception, in your case the NotFoundException:
throw new NotFoundException();
See also the chapter about exceptions in the cook book.
try this
if ($this->Session->read('Auth.User.role') == 'P' || $this->Session->read('Auth.User.role') == 'U') {
//die('you are not allowed to access this page');
//throw new ForbiddenException;
throw new NotFoundException('404 Error - Page not found');
}

Resources