#actually it's uncaught syntax error
Explore tagged Tumblr posts
elumish · 15 days ago
Text
Every time I think about the fact that whatever is wrong with my code is no doubt fixable in about 5 minutes by someone who knows what they're doing, I have to grit my teeth and go it's a learning experience it's a learning experience it's a learning experience.
20 notes · View notes
blogging-from-itp · 5 years ago
Text
Interfacing with an API to show data
Part 1:
I started by doing a step by step of Tania’s tutorial of how to connect an API with javascript.
Briefly, there are five major steps.
Set up the HTML, CSS and Javascript file. The code is already there so you can just copy the whole thing.
Set up the Javascript file. This is where you need to mention XMLHttpRequest Get request and URL of the API endpoint.
Then add an if statement to check if there are any errors and if yes then what type is it.
Now introduce the Json.parse to convert JSON into Javascript object.
Finally, to display the data, we will use DOM for Javascript to communicate with HTML. Once done, you should be able to recreate this page.
Tumblr media
Note, there is a broken image on the top left because I didn’t download the actual logo.
Part 2
I decided to stick to making a basic weather app - with a search option and weather data. If time permits, add some nice weather animation. Nothing fancy, mainly because I am in the middle of a difficult housing situation that has left me with limited time. Also, there are a lot of new terms and concepts that I am still getting acquainted with. So I decided to keep things simple and understand all the steps that I am doing well.
This is a simple sketch I used as a starting inspiration.
Tumblr media
Next, I searched for code examples that used the weather API. I have attached all the links below.
Links
Refcode available here.
Link to weather API.
CSS gradient link.
Animated illustrations link.
So the first thing I did was to get the API from openweather.org.
Tumblr media
Next is the gradient, I tried to customise my gradient using the CCS Gradient. 
Tumblr media Tumblr media
Now that this is working, what I want next is to have a dynamic background and image based on temperature like this, without the card or tabs:
Tumblr media
Since this is from Copepen, every time I tried running the code locally, I realized that it was showing an uncaught .container error and the image splits like this:
Tumblr media
Based on the guidance of Ashwita, I started searching for specific error issues and unknown syntax types like the line below:
var container = $(".container"); var backSVG = Snap("#back");
I also searched for the following areas:
1. How to call a functino in the DOM? 2. jQuery CDN 3. Uncaught Reference Error: $ is not defined 4. javascript - Uncaught Reference Error: snap is not defined 5. Uncaught Reference Error: Snap is not defined 6. Using Snap in Jquery
This is what the new updated code looks like.
The next step is to insert the weather-based elements into my main code. As you notice below, the screen seems to be split into 2. Now, this is where it gets tricky. The Codepen code includes syntax that I am not familiar with so I decided to do this through elimination.
Tumblr media
Current status. After more discussion, I realized that while rewriting the code is a great idea, it’s not something that I can achieve in the limited time I have. So I decided to skip this part and merge the CSS and HTML code and spend the rest of the time to understand the Js file line by line including how the animation is happening in the first place.
Ideal goal: I would like the weather-related animation to play in. the background depending on the adjective.
0 notes
faizrashis1995 · 5 years ago
Text
5 Advanced Java Debugging Techniques Every Developer Should Know About
Production debugging is hard, and it’s getting harder. With architectures becoming more distributed and code more asynchronous, pinpointing and resolving errors that happen in production is no child’s game. In this article we’ll talk about some advanced techniques that can help you get to the root cause of painful bugs in production more quickly, without adding material overhead to your already busy production environment.
 Better jstacks. jstack has been around for a long time (about as long as the JVM’s been around) and even to this day remains a crucial tool in every developer’s arsenal. Whenever you’re staring at a Java process that’s hung or not responding, it’s your go-to tool to see the stack trace of each thread. Even so, jstack has a couple of disadvantages that detract from its ability to help you debug complex issues in production. The first is that while it tells you what each thread is doing through its stack trace, it doesn't tell what you why it’s doing it (the kind of information usually only available through a debugger); and it doesn’t tell you when it started doing it.
 Fortunately enough, there’s a great way you can fix that, and make a good tool even better, by injecting dynamic variable state into each thread’s data. The key to this problem lies in one of the most unexpected places. You see, at no point in it’s execution does jstack query the JVM or the application code for variable state to present. However there is one important exception, which we can leverage to turn lemons into lemonade, and that is - the Thread.Name() property, whose value is injected into the stack dump. By setting it correctly you can move away from uninformative jstack thread printouts that looks like this
 “pool-1-thread-1″ #17 prio=5 os_prio=31 tid=0x00007f9d620c9800 nid=0x6d03 in Object.wait() [0x000000013ebcc000]
 Compare that with the following thread printout that contains a description of the actual work being done by the thread, the input parameters passed to it, and the time in which it started processing the request:
 ”pool-1-thread- #17: Queue: ACTIVE_PROD, MessageID: AB5CAD, type: Analyze, TransactionID: 56578956, Start Time: 10/8/2014 18:34″
 Here’s an example for how we set a stateful thread name:
 private void processMessage(Message message) { //an entry point into your code
 String name = Thread.currentThread().getName();
 try {
  Thread.currentThread().setName(prettyFormat(name, getCurrTranscationID(),
                message.getMsgType(), message.getMsgID(), getCurrentTime()));
  doProcessMessage(message);
 }
 finally {
  Thread.currentThread().setName(name); // return to original name
 }
}
In this example, where the thread is processing messages out of a queue, we see the target queue from which the thread is dequeuing messages, as well as the ID of the message being processed, and the transaction to which it is related (which is critical for reproducing locally), and last, but far from least - the time in which the processing of this message began. This last bit of information enables you to look at a server jstack with upwards of a hundred worker threads, and see which ones started first and are most likely causing an application server to hang.
 (Click on the image to enlarge it)
   An example of how an enhanced jstack shows dynamic variable state for each thread in the dump. Thread start time is marked as TS.
 The capability works just as well when you’re using a profiler, a commercial monitoring tool, a JMX console, or even Java 8’s new Mission Control. In all of these cases, your ability to look at the live thread state, or a historic thread dump, and see exactly what each thread is doing and when it started is materially enhanced by having stateful thread contexts.
   This thread variable state will also be shown by any JDK or commercial debugger or profiler.
 But the value of Thread names doesn’t stop there. They play an even bigger role in production debugging - even if you don’t use jstack at all. One instance is the global Thread.uncaughtExceptionHandler callback which serves as a last line of defense before an uncaught exception terminates a thread (or is sent back to the thread-pool).
 By the point an uncaught exception handler is reached, code execution has stopped and both frames and variable state have already been rolled back. The only state that remains for you to log the task that thread was processing, it’s parameters and starting time is captured by you guessed it - a stateful Thread name (and any additional TLS variables loaded onto it).
 Its important to keep in mind that a threading framework might implicitly catch exceptions without you knowing it. A good example is ThreadPoolExecutorService, which catches all exceptions in your Runnable and delegates them to its afterExecute method, which you can override to display something meaningful. So whatever framework you use, be mindful that if a thread fails you still have a chance to log the exception and thread state to avoid tasks disappearing into the ether.
 Throughput and deadlock jstacks. Another disadvantage of tools like jstack or Mission Control is that they need to be activated manually on a target JVM which is experiencing issues. This reduces their effectiveness in production where 99% of the time when issues occur you’re not there to debug.
 Happily enough there’s a way by which you can activate jstack programmatically when your application’s throughput falls under a specific threshold or meets a specific set of conditions. You can even automatically activate jstack when your JVM deadlocks to see exactly which threads are deadlocking and what all the other threads are doing (coupled of course with dynamic variable state for each one, courtesy of stateful thread names). This can be invaluable as deadlocking and concurrency issue are sporadic for the most part and notoriously hard to reproduce. In this case by activating jstack automatically at the moment of deadlock, one which also contains the stateful information for each thread can be a huge catalyst in your ability to reproduce and solve these kinds of bugs.
 Click here to learn more about how to automatically detect deadlocks from within your application.
 Capturing live variables. We’ve talked about ways of capturing state from the JVM through thread contexts. This approach, however effective, is restricted to variables that you had to format into the thread name in advance. Ideally, we want to be able to go in and get the value of any variable from any point in the code from a live JVM, without attaching a debugger or redeploying code. A great tool that’s been around for a while, but hasn’t got the recognition it deserves, lets you do just that; and that tool is BTrace.
 BTrace is a helpful tool that lets you run Java-like scripts on top of a live JVM to capture or aggregate any form of variable state without restarting the JVM or deploying new code. This enables you to do pretty powerful things like printing the stack traces of threads, writing to a specific file, or printing the number of items of any queue or connection pool and many more.
 This is done using BTrace scripting, a Java-like syntax in which you write functions that are injected into the code in locations of your choice through bytecode transformation (a process we’ll touch on below). The best way to try out the tool is to attach its sample scripts into a live application. Usage is very straightforward, from your command line simply enter - btrace <JVM pid> <script name>.There’s no need to restart your JVM.
 BTrace is very well documented and comes with many sample scripts (see below) to cover various common debugging scenarios around IO, memory allocation and class loading. Here are a couple of powerful examples of things you can do very easily with BTrace -
  NewArray.java: Print whenever a new char[] is allocated, and also add your own conditions based on its value. Pretty handy for selective memory profiling.
FileTracker.java: Print whenever the application writes to a specific file location. Great for pinpointing the cause of excessive IO operations.
Classload.java: React whenever a target class is loaded into the JVM. Very useful for debugging “jar-hell” situations.
BTrace was designed as a non-intrusive tool, which means it cannot alter application state or flow control. That’s a good thing, as it reduces the chances of us negatively interfering with the execution of live code and makes its use in production much more acceptable. But this capability comes with some heavy restrictions - you can’t create objects (not even Strings!), call into your or 3rd party code (to perform actions such as logging), or even do simple things such as looping for fear of creating an infinite loop. To be able to do those you’ll have to use the next set of techniques - writing your own Java agent.
 A Java agent is a jar file that provides access by the JVM to an Instrumentation object to enables you to modify bytecode that has already been loaded into the JVM to alter its behaviour. This essentially lets you “rewrite” code that is already loaded and compiled by the JVM, without restarting the application or changing the .class file on disk. Think about it like BTrace on steroids - you can essentially inject new code anywhere in your app into both your code and 3rd party code to capture any piece of information you want.
 The biggest downside to writing your own agent is that unlike BTrace, which lets you write Java-like scripts to capture state, Java agents operate at the bytecode level. This means that if you want to inject code into an application you’ll have to create the right bytecode. This can be tricky because bytecode can be hard to produce and read, following an operator stack-like syntax which is similar in many ways to Assembly language. And to make things harder, since bytecode is already compiled, any miscorrelation to the location in which it is injected will be rejected without much fanfare by the JVM’s verifier.
 To assist with this, many bytecode generation libraries have been written over the years such as JavaAssist and ASM (which is my personal favorite). A great hack which I find myself using quite a lot uses the ASM byteview IDE plugin, which lets you type any Java code in your editor and automatically generate the right ASM code to then generate it’s equivalent bytecode, which you can copy and paste into your agent.
 Click here for a real-world example of a sample agent we used to detect and sporadic memory leaks coming from 3rd party code on our server - correlating it to application state.
   Dynamically generating bytecode generation scripts from your IDE using the ASM bytecode plugin.
 The last technique I’d like to touch on briefly is building Native JVM agents. This approach uses the JVM TI C++ API layer, which gives you unprecedented control and access into the internals of the JVM. This includes things like getting callbacks whenever GC starts and stops, whenever new threads are spawn, monitors are acquired, and many more low-level capabilities. This is by far the most powerful approach to acquire state from running code, as you are essentially running at the JVM level.
 But with great power comes great responsibility, and some pretty complex challenges make this approach relatively harder to implement. The first is that since you’re running at the JVM level you're no longer writing in cross platform Java, but in low-level platform dependant C++. The second disadvantage is that the APIs themselves, while extremely powerful, are hard to use and can impact performance significantly, depending on the specific set of capabilities you’re consuming.
 On the plus side, if used correctly, this layer provides terrific access to parts of the JVM which would otherwise be closed to us in our search of the root cause of production bugs. When we began writing Takipi for production debugging, I’m not sure we knew the extent to which TI would play a crucial role in our ability to build the tool. The reason for that is that through the use of this layer you’re able to detect exceptions, calls into the OS or map application code without manual user instrumentation. If you have the time to take a look at this API layer - I highly recommend it, as it opens a unique window into the JVM not many of us know.[Source]-https://www.infoq.com/articles/Advanced-Java-Debugging-Techniques/
We provide the best Advanced Java training in navi mumbai. We have industry experienced trainers and provide hands on practice. Basic to advanced modules are covered in training sessions.
0 notes
mbaljeetsingh · 7 years ago
Text
Top 10 JavaScript Errors From 1000+ Projects (and How to Avoid Them)
To give back to our community of developers, we looked at our database of thousands of projects and found the top 10 errors in JavaScript. We’re going to show you what causes them and how to prevent them from happening. If you avoid these "gotchas," it'll make you a better developer.
Because data is king, we collected, analyzed, and ranked the top 10 JavaScript errors. Rollbar collects all the errors for each project and summarizes how many times each one occurred. We do this by grouping errors according to their fingerprints. Basically, we group two errors if the second one is just a repeat of the first. This gives users a nice overview instead of an overwhelming big dump like you’d see in a log file.
We focused on the errors most likely to affect you and your users. To do this, we ranked errors by the number of projects experiencing them across different companies. If we looked only at the total number of times each error occurred, then high-volume customers could overwhelm the data set with errors that are not relevant to most readers.
Here Are the Top 10 JavaScript Errors:
Each error has been shortened for easier readability. Let’s dive deeper into each one to determine what can cause it and how you can avoid creating it.
1. Uncaught TypeError: Cannot Read Property
If you’re a JavaScript developer, you’ve probably seen this error more than you care to admit. This one occurs in Chrome when you read a property or call a method on an undefined object. You can test this very easily in the Chrome Developer Console.
This can occur for many reasons, but a common one is the improper initialization of state while rendering the UI components. Let’s look at an example of how this can occur in a real-world app. We’ll pick React, but the same principles of improper initialization also apply to Angular, Vue or any other framework.
There are two important things realize here:
A component’s state (e.g. this.state) begins life as undefined.
When you fetch data asynchronously, the component will render at least once before the data is loaded – regardless of whether it’s fetched in the constructor, componentWillMount or componentDidMount. When Quiz first renders, this.state.items is undefined. This, in turn, means ItemList gets items as undefined, and you get an error – "Uncaught TypeError: Cannot read property ‘map’ of undefined" in the console.
This is easy to fix. The simplest way: Initialize state with reasonable default values in the constructor.
The exact code in your app might be different, but we hope we’ve given you enough of a clue to either fix or avoid this problem in your app. If not, keep reading because we’ll cover more examples of related errors below.
2. TypeError: ‘undefined’ Is Not an Object (evaluating...)
This is an error that occurs in Safari when you read a property or call a method on an undefined object. You can test this very easily in the Safari Developer Console. This is essentially the same as the above error for Chrome, but Safari uses a different error message.
3. TypeError: Null Is Not an Object (evaluating...)
This is an error that occurs in Safari when you read a property or call a method on a null object. You can test this very easily in the Safari Developer Console.
Interestingly, in JavaScript, null and undefined are not the same, which is why we see two different error messages. Undefined is usually a variable that has not been assigned, while null means the value is blank. To verify they are not equal, try using the strict equality operator:
One way this error might occur in a real-world example is if you try using a DOM element in your JavaScript before the element is loaded. That’s because the DOM API returns null for object references that are blank.
Any JS code that executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as laid out in the HTML. So, if there is a tag before the DOM elements, the JS code within the script tag will execute as the browser parses the HTML page. You will get this error if the DOM elements have not been created before loading the script.
In this example, we can resolve the issue by adding an event listener that will notify us when the page is ready. Once the addEventListener is fired, the init() method can make use of the DOM elements.
4. (unknown): Script Error
The Script error occurs when an uncaught JavaScript error crosses domain boundaries in violation of the cross-origin policy. For example, if you host your JavaScript code on a CDN, any uncaught errors (errors that bubble up to the window.onerror handler, instead of being caught in try-catch) will get reported as simply "Script error" instead of containing useful information. This is a browser security measure intended to prevent passing data across domains that otherwise wouldn’t be allowed to communicate.
To get the real error messages, do the following:
1. Send the Access-Control-Allow-Origin header
Setting the Access-Control-Allow-Origin header to * signifies that the resource can be accessed properly from any domain. You can replace * with your domain if necessary: for example, Access-Control-Allow-Origin: www.example.com. However, handling multiple domains gets tricky, and may not be worth the effort if you’re using a CDN due to caching issues that may arise. See more here.
Here are some examples of how to set this header in various environments:
Apache
In the folders where your JavaScript files will be served from, create an .htaccess file with the following contents:
Nginx
Add the add_header directive to the location block that serves your JavaScript files:
HAProxy
Add the following to your asset backend where JavaScript files are served from:
2. Set crossorigin="anonymous" on the script tag
In your HTML source, for each of the scripts that you’ve set the Access-Control-Allow-Origin header for, set crossorigin="anonymous" on the SCRIPT tag. Make sure you verify that the header is being sent for the script file before adding the crossorigin property to the script tag. In Firefox, if the crossorigin attribute is present but the Access-Control-Allow-Origin header is not, the script won’t be executed.
5. TypeError: Object Doesn’t Support Property
This is an error that occurs in IE when you call an undefined method. You can test this in the IE Developer Console.
This is equivalent to the error "TypeError: ‘undefined’ is not a function" in Chrome. Yes, different browsers can have different error messages for the same logical error.
This is a common problem for IE in web applications that employ JavaScript namespacing. When this is the case, the problem 99.9% of the time is IE’s inability to bind methods within the current namespace to the this keyword. For example, if you have the JS namespace Rollbar with the method isAwesome. Normally, if you are within the Rollbar namespace you can invoke the isAwesome method with the following syntax:
Chrome, Firefox, and Opera will happily accept this syntax. IE, on the other hand, will not. Thus, the safest bet when using JS namespacing is to always prefix with the actual namespace.
6. TypeError: ‘undefined’ Is Not a Function
This is an error that occurs in Chrome when you call an undefined function. You can test this in the Chrome Developer Console and Mozilla Firefox Developer Console.
As JavaScript coding techniques and design patterns have become increasingly sophisticated over the years, there’s been a corresponding increase in the proliferation of self-referencing scopes within callbacks and closures, which are a fairly common source of this/that confusion.
Consider this example code snippet:
Executing the above code results in the following error: "Uncaught TypeError: undefined is not a function." The reason you get the above error is that when you invoke setTimeout(), you are actually invoking window.setTimeout(). As a result, an anonymous function being passed to setTimeout() is being defined in the context of the window object, which has no clearBoard() method.
A traditional, old-browser-compliant solution is to simply save your reference to this in a variable that can then be inherited by the closure. For example:
Alternatively, in the newer browsers, you can use the bind() method to pass the proper reference:
7. Uncaught RangeError: Maximum Call Stack
This is an error that occurs in Chrome under a couple of circumstances. One is when you call a recursive function that does not terminate. You can test this in the Chrome Developer Console.
It may also happen if you pass a value to a function that is out of range. Many functions accept only a specific range of numbers for their input values. For example, Number.toExponential(digits) and Number.toFixed(digits) accept digits from 0 to 20, and Number.toPrecision(digits) accepts digits from 1 to 21.
8. TypeError: Cannot Read Property ‘length’
This is an error that occurs in Chrome because of reading length property for an undefined variable. You can test this in the Chrome Developer Console.
You normally find length defined on an array, but you might run into this error if the array is not initialized or if the variable name is hidden in another context. Let’s understand this error with the following example.
When you declare a function with parameters, these parameters become local ones. This means that even if you have variables with names testArray, parameters with the same names within a function will still be treated as local.
You have two ways to resolve your issue:
Remove parameters in the function declaration statement (it turns out you want to access those variables that are declared outside of the function, so you don’t need parameters for your function):
Invoke the function passing it the array that we declared:
9. Uncaught TypeError: Cannot Set Property
When we try to access an undefined variable it always returns undefined and we cannot get or set any property of undefined. In that case, an application will throw “Uncaught TypeError cannot set property of undefined.”
For example, in the Chrome browser:
If the test object does not exist, the error will throw “Uncaught TypeError cannot set property of undefined.”
10. ReferenceError: Event Is Not Defined
This error is thrown when you try to access a variable that is undefined or is outside the current scope. You can test it very easily in Chrome browser.
If you’re getting this error when using the event handling system, make sure you use the event object passed in as a parameter. Older browsers like IE offer a global variable event, but it's not supported on all browsers. Libraries like jQuery attempt to normalize this behavior. Nevertheless, it’s best practice to use the one passed into your event handler function.
Conclusion
We hope you learned something new and can avoid errors in the future, or that this guide helped you solve a head-scratcher. Nevertheless, even with the best practices, unexpected errors do pop up in production. It's important to have visibility into errors that affect your users and to have good tools to solve them quickly.
 This article was originally published on Rollbar's blog.
via DZone Web Dev Zone http://ift.tt/2DYa4Xl
0 notes