Node server crashes in parsing JSON - json

Looks like my node server dies in parseJSON.
Looked at the logs and the last message was "before parse" and it never printed "after parse". What's strange is that I wrapped JSON.pars with try-catch so I am not sure how it caused the server crashed. Any thoughts?
logger.print("before parse")
parseJSON(data)
logger.print("after parse")
and I have pareJSON catch exception.
function parseJSON(str) {
try {
var result = JSON.parse(str);
return result;
} catch (err) {
return null
}
}

If your code crashes in parseJSON then I would try:
try {
logger.print("before parse")
parseJSON(data)
logger.print("after parse")
} catch (e) {
console.log(e);
}
It is strange because your function should catch the exception but this would show what happens. I would also add:
console.log(data.length);
to see the size of the data.
Also I wrote a module tryjson that parses JSON without throwing exceptions. You can try using it but if your function crashes then maybe my module would not handle it either. Though I'd love to know what actually happens.

Related

react native- json parsing (cant parse json object in my code)

Here is my code. In this I got x but when I try to parsing x for getting object of x 'isloggedin' it gives error. what should I do wrong tell me if you understand my problem.
componentDidMount() {
this.onLoad();
}
onLoad = async () => {
try {
var walletdata = await AsyncStorage.getItem('wallet');
this.setState({x: JSON.parse(walletdata)})
this.setState({y: JSON.stringify(this.state.x)})
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
}catch(error){
console.log("error: "+error);
}
}
error: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
Probably is because 'wallet' key has undefined value in the caché storage. You should check first the value (right after getting the item from the storage) and if it's undefined then you have to set it first.
Probably you need to wait for the first setState function to finish, So that you can get access to it in second call.
In short, It will take some time for setting your value in State and you are trying to access it before updating the state. So try to access the values in the callback of setState function.
Instead of this,
this.setState({x: JSON.parse(walletdata)})
this.setState({y: JSON.stringify(this.state.x)})
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
You can use this:
this.setState({x: JSON.parse(walletdata),y: JSON.stringify(walletdata.x)},()=>{
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
});
I have solved my problem. Thank you for your answers. below is how could I solved my question.
try {
var walletdata = await AsyncStorage.getItem('wallet');
this.setState({wallet: JSON.stringify(JSON.parse(walletdata))})
this.setState({isLoggedin:JSON.parse
(this.state.wallet).isLoggedin});
console.log(this.state.isLoggedin);
}catch(error){
console.log("error: "+error);
}

Hel­p with actionscript 3 syntax

I would like your help here, this is my actionscript3 code.
Everytime I compile I get error.
Line 1537 1073: Syntax error: expecting a catch or a finally clause.
This is the code
{
try
{
}
_loc_3.badge.gotoAndStop(param1.split(":")[2]);
}
And the second error
{
try
{
}
_loc_3.badge.gotoAndStop(param1.split(":")[2]);
}
The second error says:
Line 1537 1084: Syntax error: expecting rightbrace before semicolon.
Could anyone help me here, thanks in advance.
UPDATE: After I add a right brace before the semicolon it gives more errors.
The first error is really explicit, you need a catch block. The empty try block is useless.
The syntax found on a website.
try {
//Your code
}
catch(e:Error) { // Error handling
trace("Error found: " + e);
}
//Optional
finally {
// Closing connection for example.
}
Website reference in french
A try cannot be used without a catch. the idea there is lets try this piece of code and if we run into any problems stop and execute the content of whatever is in the catch. the finally is used for executing code that you want to run regardless of whether the try or catch gets executed.
in the first error:
you are just missing a catch. also maybe include some code into the try statement, otherwise its pointless to use.
example:
try
{
//try to feed my dog
feedDog();
}
//if some error occurs in feedDog() then the catch will be called
//if you want to catch specific exceptions
//then specify its type instead of Exception
catch (Exception e)
{
trace("unable to feed dog");
}
//this will execute whether the dog was fed successfully or not
finally
{
trace("leave");
}
with the second error: you are probably missing a '}' somewhere in that function. Indent your code so that these will become clearly visible to you and you can match every '{' with its corresponding '}'

Catch exception in node during JSON.parse

My node server dies when it is unable to parse JSON in the following line:
var json = JSON.parse(message);
I read this thread on how to catch exceptions in node, but I am still not sure what is the proper way to wrap a try and catch block around this statement. My goal is to catch the exception and log an error to the console, and of course keep the server alive. Thank you.
It's all good! :-)
JSON.parse runs synchronous and does not know anything about an err parameter as is often used in Node.js. Hence, you have very simple behavior: If JSON parsing is fine, JSON.parse returns an object; if not, it throws an exception that you can catch with try / catch, just like this:
webSocket.on('message', function (message) {
var messageObject;
try {
messageObject = JSON.parse(message);
} catch (e) {
return console.error(e);
}
// At this point, messageObject contains your parsed message as an object.
}
That's it! :-)

How do I log an error with ELMAH when catching an error for proper JSON formatting in MVC 3

I have an ASP.NET MVC 3 application where I'm making an AJAX call and expecting a JSON result back. I'm using ELMAH to log errors. While testing I had an unexpected error. ELMAH logged the error, but my client side script doesn't because the result is not proper JSON now. If I handle all errors in the controller to return a proper JSON result, then the error doesn't get logged by ELMAH. I know I can call ELMAH specifically to log the error, but I rather like that I don't have to do that anywhere else.
Can anyone clarify the 'proper' way to handle this scenario?
for example
try
{
//service.dosomethingwitherror();
return new JsonResult { Data = new { result = true, message = "Success." } };
}
catch (Exception ex)
{
return new JsonResult { Data = new { result = true, message = "Failed." } };
}
Since I'm 'handling' this, ELMAH doesn't log. If I don't handle this my client won't get JSON...
You can use the ErrorSignal class to log manually. This will perform all configured elmah operations (log, mail, tweet, etc).
ErrorSignal.FromCurrentContext().Raise(new NotSupportedException());
See http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Signaling_errors for more information.
If you really don't like adding that code to your controller, you could not catch the exception server side and handle the ajax error event in your javascript.

Kohana_Request_Exception [ 0 ]: Unable to find a route to match the URI:

i have a kohana site and i want to put it into production, but i have a problem i don't know how to solve best:
if someone accesses a uri that doesn't exist, relatively to my website, an error page appears, with the header message:
Kohana_Request_Exception [ 0 ]: Unable
to find a route to match the URI: (and the uri here)
i wonder if I can do something to redirect the user to a standard 404 page, when he/she accesses such a URI,can I?
thank you very much!
You can wrap your $request->execute() in your APPPATH/bootstrap.php with a try/catch block and then do whatever you want.
Mine looks like this...
try
{
// Attempt to execute the response
$request->execute();
}
catch (Kohana_Request_Exception $e)
{
if (Kohana::$environment === Kohana::DEVELOPMENT) throw $e;
// Log the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Create a 404 response
$request->status = 404;
$request->response = Request::factory('errors/404')->execute();
}
catch (Exception $e)
{
if (Kohana::$environment === Kohana::DEVELOPMENT) throw $e;
// Log the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Create a 500 response
$request->status = 500;
$request->response = Request::factory('errors/500')->execute();
}
Ideally PHP would support finally { ... } and I could do the logging and possible re-throwing there, but what can you do?
You can handle all errors the same way it is described in the userguide for http exceptions:
http://kohanaframework.org/3.1/guide/kohana/errors#http-exception-handling
Try out this one
define('IN_PRODUCTION', TRUE);
// Instantiate your Request object
$request = Request::instance();
try
{
$request->execute();
}
catch (Exception $e) // if its not valid, it gets caught here
{
if (! IN_PRODUCTION) // if this is Development, its displays the error
{
throw $e;
}
// if its IN_PRODUCTION, it does the following:
// Logs the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Marks the status as 404
$request->status = 404;
$request->response = $request->factory('sitemap')->execute();
}
// then continues on with the request process to display your custom 404 page
$request->send_headers()->response;
echo $request->response;