Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw a javascript error during runtime via browser (Chrome)?

My objective: Test out my error handling functionality.

Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.

var a = undefined;
a.b.c // Breaks.

The above works, but I can't use it to test production site as the page is not required. I was looking for a way to test it via the browser. I tried simply adding" throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.

I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.

Any other easier ways to do this rather than the above?

I was looking for a way where I can do it via browser only.

Thanks.

like image 906
Nevin Madhukar K Avatar asked Jan 25 '23 05:01

Nevin Madhukar K


1 Answers

You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:

  • Open the webpage
  • Open Chrome developer tools for that webpage
  • In Sources panel go to Overrides tab
  • Click Select folder for overrides and choose a folder on your computer
    • A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
  • In Sources panel go to Page tab
  • Locate the file in which you need to inject the "throw error" code
  • Right click and choose Save for overrides

Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.

like image 171
Salman A Avatar answered Jan 28 '23 13:01

Salman A