Get line number of an error in JScript run in Windows Script Host - wsh

Say, I have the following code that I run as a .JS file using the Windows Script Host:
try
{
ProduceAnError();
}
catch(e)
{
//How to get an error line here?
}
Is there any way to know the error line where an error (exception) occurred?

Sorry for my other reply. It wasn't very helpful :P
I believe what you are looking for is the ReferenceError's stack property. You can access it with the argument that you pass to the catch:
try {
someUndefinedFunction("test");
} catch(e) {
console.log(e.stack)
}
example output:
ReferenceError: someUndefinedFunction is not defined
at message (http://example.com/example.html:4:3)
at <error: TypeError: Accessing selectionEnd on an input element that cannot have a selection.>
at HTMLInputElement.onclick (http://example.com/example.html:25:4)

There isn't really a way to get a stack or even catch the line number programmatically. One can only see the line number when throwing an error. At best you can get the error code and description or you can make your own errors.
Here's the documentation.
And an example
try {
produceAnError();
} catch(e) {
WScript.echo((e.number>>16 & 0x1FFF)); // Prints Facility Code
WScript.echo((e.number & 0xFFFF)); // Prints Error Code
WScript.echo(e.description); // Prints Description
throw e;
}

Related

Jenkinsfile: Why `java.lang.NoSuchMethodError: No such DSL method` is not caught?

I have the following code in the Jenkinsfile which calls an "optional" method, and if it does not exists it just shall print a message
...
try {
verifyDeployment(pipelineParams)
} catch (err) {
echo "[INFO] No `verifyDeployment` defined, thus ignoring this step"
}
...
However when I run the pipeline the catch seems not to work at I get the following error:
java.lang.NoSuchMethodError: No such DSL method 'verifyDeployment' found among steps
What do I miss?
You are using a wrong groovy syntax.
See the correct groovy syntax for catching exceptions: Syntax catching exceptions
try {
//Protected code
} catch(ExceptionName e1) {
//Catch block
}
It turns out you need to explicitly catch NoSuchMethodError as follows
...
try {
verifyDeployment(pipelineParams)
} catch (NoSuchMethodError ex) {
echo "[INFO] No `verifyDeployment` defined, thus ignoring this step"
}
...
You can also be more generic with the catching type and
catch (Throwable ex)
See the type hierarchy:
https://docs.oracle.com/javase/7/docs/api/java/lang/NoSuchMethodError.html
But be sure to read up on "catch throwable practice" and decide if it's right for you. I sometimes catch throwable only for logging followed by a rethrow.

Get the stack trace of exception in Rhino

We have an app that allows to enter a scripts. These scripts can be in multiple files, so when there is an exception we want to be able to show a stack trace to the app admin so he can diagnose the issue.
Is there there a way to extract the stack trace from a Rhino exception?
First of all, in order to get a good stack trace, you need to be very careful when evaluating scripts in your scope. I've seen that this is overlooked by many developers where they always send the same params for sourceName and lineno, like:
ctx.evaluateString(scriptScope, script, "script", 0, null);
So in the 3rd and 4th params you have to send the file name of something that will help the developer identify the script. Then, the line number should be correct, in case you concatenate scripts.
So, once you evaluate all the scripts in your context correctly, you can be able to get a useful stack track. So just catch the exception and process the info in the stack trace:
try {
// execute script
} catch (RhinoException re) {
StackTraceElement[] stackTrace = re.getStackTrace();
if (stackTrace != null) {
for (StackTraceElement stackElement : stackTrace) {
// stackElement.getFileName();
// stackElement.getLineNumber();
}
}
}

Is it possible to change the output of Lua error messages?

I managed to change the output of error messages by modifying the dbg_printf method. However, that method doesn't handle the following error messages:
lua: ?:0: attempt to call global 'log' (a nil value)
Which method(s) handle these types of errors?
The error message is from the file ldebug.c in the function luaG_typeerror. But i guess you are using an older Lua Version because my message is a bit different:
attempt to call a nil value (global 'log')
You sould try to prevent the error if you can:
if type(log) == "function" then
log()
end
or as #lhf said use pcall:
if pcall(log) then
-- no errors while running 'log'
...
else
-- 'log' raised an error: take appropriate actions
...
end
It should be simpler than digging into the C api.
like #lhf says:
if pcal(risky) then
print("this works")
else
print("phooey!")
end
alternatively you can stop the program and get your error message like this:
if pcal(risky) then
print("this works")
else
error("your error message here")
end

How to gracefully abort yeoman generator on error?

I'm writing a yeoman generator and want to check some prerequisites, for example a git being installed. I can easily check this using .exec, but how do i gracefully abort generator and report error to user? I searched docs, but it seems that i'm missing some obvious way to do it. Any hints?
Throwing exception will of course abort generator, but is it a best way? Maybe something more user friendly? Not all yeoman users are able to read js exceptions.
The current state of error handling in the popular generators is quite diverse:
in the most cases they just log the error and return from the action and let the subsequnt actions run and return 0 status code:
generator-karma's setupTravis method:
if (err) {
this.log.error('Could not open package.json for reading.', err);
done();
return;
}
or set a custom abort property on error and skip further actions with cheking on the abort property but still return 0 status code:
generator-jhipster's CloudFoundryGenerator:
CloudFoundryGenerator.prototype.checkInstallation = function checkInstallation() {
if(this.abort) return;
var done = this.async();
exec('cf --version', function (err) {
if (err) {
this.log.error('cloudfoundry\'s cf command line interface is not available. ' +
'You can install it via https://github.com/cloudfoundry/cli/releases');
this.abort = true;
}
done();
}.bind(this));
};
or manually end the process with process.exit:
generator-mobile's configuringmethod:
if (err) {
self.log.error(err);
process.exit(1);
}
However none of these methods provide a good way to signal to the environment that something went wrong except the last one but directly calling process.exit is a design smell.
Throwing an exception is also an option but this presents also the stackstrace to the user which is not always a good idea.
The best option would be use the Environment.error method, which has some nice advantages:
the Environment is exposed thorough the env property of the yeoman.generators.Base
an error event is emitted which is handled by the yo cli code
the execution will result in a non zero (error) status code which is override-able
by default yo will display only the message and no stacktrace
the stacktrace can be optionally displayed with providing the --debug built-in option when re-running the generator.
With using this technique your action method would look like this:
module.exports = generators.Base.extend({
method1: function () {
console.log('method 1 just ran');
this.env.error("something bad is happened");
console.log('this won't be executed');
},
method2: function () {
console.log('this won't be executed');
}
});

Send email everytime php generates a fatal error

How would I write a PHP code that would send me an email everytime I get a
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 14373306 bytes) in on line <b>443</b><br />.
I'm running a script wherein a user has this URL and it will be process by my code, but the problem here is that sometimes it results to a Fatal error Allowed memory size exhausted. I want an email to be sent to me that tells me that there has this error at the same time what URL is causing that error.
So the logic is something like this.
if( error == "Fatal Error Allowed memory Size" ) {
mail("myemail#email.com", "Fatal Error - URL: http://google.com");
}
I hope the instruction is pretty clear. Your help would be greatly appreciated and rewarded!
Thanks! :-)
You can look at using register_shutdown_function(). It can be used to execute on E_ERROR(fatal error)
register_shutdown_function('shutdown');
function shutdown()
{
if(!is_null($e = error_get_last()))
{
mail("myemail#email.com", "Fatal Error - ". var_export($e, true));
}
}
I would however echo thoughts in the comments above that this is best handled using log monitoring.
Init following function inside your php file.
register_shutdown_function('mail_on_error'); //inside your php script
/** If any file having any kind of fatal error, sln team will be notified when cron will
become fail : following is the name of handler and its type
E_ERROR: 1 | E_WARNING: 2 | E_PARSE: 4 | E_NOTICE: 8
*/
function mail_on_error() {
global $objSettings;
$error = error_get_last();
//print_r($error);
if ($error['type'] == 1) {
// update file path into db
$objSettings->update_records($id=1,array('fatal_error' => json_encode($error)));
$exception_in_file_path = __FILE__;
fatal_error_structure($exception_in_file_path);
}// end if
}// end mail_on_error
fatal_error_structure should be defined on some global location. like function.inc.php. This will send an email to registered user.
function fatal_error_structure($exception_in_file_path){
$subject = "FATAL: Cron Daemon has failed";
sln_send_mail(nl2br("Please check $exception_in_file_path, This cron having FATAL error."),
$subject, 'email#address.com',$name_reciever='', 'text/plain');
}// end fatal_error_structure
vKj

Resources