Capture error in jQuery


I have the following doubt. I have always worked jQuery looking for all the possible falls by mistake, and avoided doing other functionalities. However, I missed the following doubt. Is there any way to rescue an error that is generated in jQuery by syntax?

Since many times I work with dynamic data, these may sometimes have a problem that I have not foreseen, and knowing if you can and how it would be helpful.

The idea is that you can take any jQuery crash, so you can take statistics measures to generate patches in future and also solve without the client having to realize that there was an error.

asked by José Miguel Sepulveda 12.04.2017 в 16:26

1 answer


In the client you can do it using eval , but its use is dangerous because it can be used for attacks like XSS. Using eval in a few words, makes your site vulnerable.

try {
} catch (e) {
  console.error('El script tiene errores');

The best option in this case would be to use a parser on the server to know if a script is valid or not. I do not know what language you use in the backend, but for example, in Node.js you can use the package syntax-error that evaluates a module (JS file) or a plain text code in search of errors and if it finds them, it reports them in detail (line where it happened).

If you use Browserify it is possible to use syntax-error in the browser. For example, if we evaluate the following:

var check = require("syntax-error");

// falta cierre de paréntesis
const e = check('console.log("b"');

// en caso hayan errores, devolverá un objeto
// caso contrario, nada (undefined)
if (e) {

It will show us the following error message:

(anonymous file):1
ParseError: Unexpected token

If you work with plugin systems or extensions, without a doubt it will be quite useful.

answered by 12.04.2017 / 17:36