Customizing exception from data provided by excel file - excel

I use Laravel 5.6 and PostgreSQL 11 in order to import data from Excel file to database. How do I customize the sqlstate error message coming from postgres and display it to user?

You should capture the exception and treat it accordingly.
An SQLState error can be captured with a catch (\Exception $e).
Check this link to learn about php exceptions if you don't know yet.
Check this other link on error handling to learn how to deal with exceptions accordingly in Laravel.

You can customize your exception using try catch.
try {
//your source code (import excel to database)
} catch(\Exception $e) {
return "your customize message put here";
}

Related

What is considered standard when dealing with database errors in a REST application?

I'm currently writing a public REST service in Node.js that interfaces with a Postgres-database (using Sequelize) and a Redis cache instance.
I'm now looking into error handling and how to send informative and verbose error messages if something would happen with a request.
It struck me that I'm not quite sure how to handle internal server errors. What would be the appropriate way of dealing with this? Consider the following scenario:
I'm sending a post-request to an endpoint which in turn inserts the content to the database. However, something went wrong during this process (validation, connection issue, whatever). An error is thrown by the Sequelize-driver and I catch it.
I would argue that it is quite sensitive information (even if I remove the stack trace) and I'm not comfortable with exposing references of internal concepts (table-names, functions, etc.) to the client. I'd like to have a custom error for these scenarios that briefly describes the problem without giving away too detailed information.
Is the only way to approach this by mapping every "possible" error in the Sequelize-driver to a generic one and send that back to the client? Or how would you approach this?
Thanks in advance.
Errors are always caused by something. You should identify and intercept these causes before doing your database operation. Only cases that you think you've prepared for should reach the database operation.
If an unexpected error occurs, you should not send an informative error message for security reasons. Just send a generic error for unexpected cases.
Your code will look somewhat like this:
async databaseInsert(req, res) {
try {
if (typeof req.body.name !== 'string') {
res.status(400).send('Required field "name" was missing or malformed.')
return
}
if (problemCase2) {
res.status(400).send('Error message 2')
return
}
...
result = await ... // database operation
res.status(200).send(result)
} catch (e) {
res.status(500).send(debugging ? e : 'Unexpected error')
}
}

How to deal with pdo errors

I have a question, in the PDO manuial somewhere I read that errors reveal the db connect with username and password (due to a flaw in the zend engine). I see several examples of catching the pdo like this:
catch(PDOException $exception){
return $exception;
}
if the exception is returned, doesn't the user see the error?
Is it better to have disabled the error reporting in the php.ini file, or even do something like
setAttribute(PDO::ERRMODE_SILENT)
instead of the catch statement, or is it better to do a combination of above and redo the catch statement so it doesn't return the error to the user.
This is referring to the pink paragraph on the manual page that says: Warning: If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler(). php.net/manual/en/pdo.connections.php.
The user "YOUR COMMON SENSE" marked this as duplicate which is not correct. I don't have an issue with using PDO, Its just a question of dealing with error responses, and correct methodology of error handling.

how to log js errors at server

I wanted to know does YUI3 provides any way to try and catch errors functionality, where in after the error is captured we can show some customized error alert and simultaneously log the error at server side with the error exceptions and other details.
Also if this functionality is not there in yui3 then which all frameworks do one need to use to do this and which all are compatible with YUI.
I'm not aware of YUI3 providing exactly what you're after out-of-the box.
You can split your question into two parts:
Capturing errors
You either wrap your code with try/catch blocks or use a global error handler. It looks like YUI3 doesn't yet directly handle this (http://yuilibrary.com/projects/yui3/ticket/2528067) but handling it shouldn't be too hard, you'll just have to test for browser differences.
Sending Error data to the server
You ought to be able to use Y.IO to send back the error data to the server. It looks like you get errorMsg, url, lineNumber given to you, so you can just send them back to the server:
YUI().use("io-base",function(Y){
window.onerror = function(errorMsg, url, lineNumber){
Y.io("/errorHandler.php", {
data: {
errorMsg: errorMsg,
url: url,
lineNumber: lineNumber
}
});
alert("Sorry, something bad happened");
};
console.log("handler registered");
//now trigger an error
a.b.c="banana";
});
That seems to work here: http://jsfiddle.net/J83LW/
I'l leave the customized alert to you, I've left an alert here as a basic example of handling this

XPages Custom Error Page - get error message and line

I'm trying to generate a custom error page for my xpages. I googled a lot of solutions and so far I get an error page telling me, that an error occured.
But I can't get the information what exactly happened (in this case the error is, that an "doc" has to be saved, but i named the variable "docs" just to get error).
All I do is:
var errObj = requestScope.error;
output = errObj.getCause().getErrorPropertyId();
output = errObj.getCause().getComponentId();
As soon as I try to call getExpressionText() I get an error 500.
How do I get the information, where the error happened (line number) and the variable that caused the error? - just like I do using the standard error page.
The error line and details are not easily accessible from requestScope.error. If you look at the source code for the latest release of Mark Leusink's Debug Toolbar, you'll see he's parsing the stack trace to get the details.
However, you can access all the relevant information using the underlying Java class for the SSJS exception - com.ibm.jscript.InterpretException using getErrorLine(). The getLocalizedMessage() method gets the error detail that usually starts "Script interpreter error". The getExpressionText() method retrieves the line that threw the error.
If you take a look at the XPages OpenLog Logger project I put on OpenNTF, that's what I use to log full details to OpenLog. http://www.openntf.org/Internal/home.nsf/project.xsp?action=openDocument&name=XPages%20OpenLog%20Logger
You can see the source code of the OpenLogPhaseListener which uses those methods here: https://github.com/paulswithers/openlogjava/blob/master/OpenLogJava/WebContent/WEB-INF/src/com/paulwithers/openLog/OpenLogPhaseListener.java
Even if you're not a Java expert, from use of SSJS the key parts should be understandable. Line 84 captures uncaught exceptions - when XPages routes to the default error page. That uses the methods I mentioned.
Lines 98 to 105 are the ones that log out all the details if you just use a catch block, passing OpenLogBean.addError(e, this) where e is the error object and this is the component the error occurs on. error.getError() in the Java code retrieves that error object. To get the typeahead in SSJS you'll need to use catch(e:com.ibm.jscript.InterpretException) I believe.
I haven't tested this, I've just working back from what I used for the project on OpenNTF.
Have a look at this XSnippet by Tony McGuckin: http://openntf.org/XSnippets.nsf/snippet.xsp?id=custom-error-page-cw-cause-and-stacktrace-information. It uses the following to output details on the error:
var output = requestScope.error.toString()+"\n\n";
if(requestScope.error instanceof com.ibm.xsp.exception.XSPExceptionInfo){
var codeSnippet = requestScope.error.getErrorText();
var control = requestScope.error.getErrorComponentId();
var cause = requestScope.error.getCause();
output += "In the control : " + control + "\n\n";
if(cause instanceof com.ibm.jscript.InterpretException){
var errorLine = cause.getErrorLine();
var errorColumn = cause.getErrorCol();
output += "At line " + errorLine;
output += ", column " + errorColumn + " of:\n";
}else{
output += "In the script:\n";
}
output += codeSnippet;
}
return output;
For now I've dealt with this problem by using the Debug Toolbar and the OpenLog Database.
If an error occurs the user only gets a custom error page (using the example of the Debug Toolbar) with the information, that something went wrong. So he does not have to bother with any other problems or even the Stack Trace. But at the same moment he gets the error page, the error is logged in our Log-Database with all informations needed (like line, exact error message etc.).
I've also implemented an "Report this problem" Link-Button to create a new E-Mail containing important information about the session the user is currently in.

PHP - One last call

Is there a way to tell PHP to run one last function, or somehow override some error handler in the event of a fatal error? I have a cron that has a main entry point of:
$obj = new obj();
$obj->run();
exit;
Would wrapping that in a try catch do the trick if I'm not explicitly throwing errors? All I want is for PHP to do something as simple as create a txt file containing the fatal error, or even just create an empty file named 'failed.txt', or something.
Thanks!
error_handler might help you here
Or this for fatal errors: http://insomanic.me.uk/post/229851073/php-trick-catching-fatal-errors-e-error-with-a
You write it's cron. Call the script with a path to a new php.ini file wherein you make PHP to log the errors to STDERR or STDOUT.
php -h
will give you all commandline options.
Cron will send you the reports then if something failed by email.
Alternatively you can set this up to log into your own log as it's a new php.ini. In case that's easier for you to review.
You can set a custom error handler for most errors, and execute some code there.
But cannot handle an E_ERROR which is what your fatal error is likely to be.
Imagine if that error was for running out of memory. You try to handle that error, and end up using more memory. Which just throws another error, and you're right where you started.
Use register_shutdown_function() to register a function to execute as the last call. This will get call whether there was an error or not.
See http://php.net/manual/function.register-shutdown-function.php for more information.
You can do custom error handling in PHP. Check the manual at: http://php.net/function.set-error-handler. This is a fairly straightforward application of that.
Use
try
{
//Code
}
catch(Exception $e)
{
//Execute on error
}

Resources