I read here in Mozilla a docs saying the try...catch conditional is
"non-standard and is not on a standards track. Do not use it on
production"
but i don't understand why.
And I want to know How can I make this statement in a situation where I can create multiple response.status for each situation. For example, this is my code now
class BookController {
async store ({ request, response }) {
try {
const values = { ...request.all(), user_id: request.user_id }
const validatedValues = await importValidate.validate(values, rules, messages)
return Book.create(validatedValues)
} catch (e) {
response.status(409).json(e)
}
}
And i need it to be multiples response.status to each situation, for each response based in my rules.
I'm currently using JS, Node, Adonis and in this validation process, Indicative/Validator
As the documentation you read already explains:
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
In such a case it would be better for you to define your own conditional statements
instead of
try {
myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
use
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
In this way you will still separately handle all the exceptions, but within a single catch statement
Related
The SpiderMonkey JavaScript engine's parser once supported a nonterminal symbol GuardedCatchClause, which when parsed would produce entries in the .guardedHandlers property of the associated TryStatement; this property also appeared in the ESTree spec at the time.
Unfortunately I have not found any references to the syntax of try statements with GuardedCatchClauses on the web. What was the actual syntax and semantics? Were these essentially catch clauses with an additional if-like conditional?
Additionally: was GuardedCatchClause part of the ES4 proposals? (I have never seen reference to this in any of the ES4 feature retrospectives I have read.)
It does refer to conditional catch clauses. You can find a description of them in the web archive of the Mozilla documentation:
Conditional catch clauses
Non-standard
This feature is non-standard and is not on a standards
track. Do not use it on production sites facing the Web: it will not
work for every user. There may also be large incompatibilities between
implementations and the behavior may change in the future.
You can also use one or more conditional catch clauses to handle
specific exceptions. In this case, the appropriate catch clause is
entered when the specified exception is thrown. In the following
example, code in the try block can potentially throw three exceptions:
TypeError, RangeError, and EvalError. When an exception occurs,
control transfers to the appropriate catch clause. If the exception is
not one of the specified exceptions and an unconditional catch clause
is found, control transfers to that catch clause.
If you use an unconditional catch clause with one or more conditional
catch clauses, the unconditional catch clause must be specified last.
Otherwise, the unconditional catch clause will intercept all types of
exception before they can reach the conditional ones.
Reminder: this functionality is not part of the ECMAScript
specification and has been removed in Firefox 59. It's not supported
in any current browser anymore.
try {
myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
Here is the same "Conditional catch clauses" using code that conforms
to ECMAScript specification (obviously it's verbose, but works
everywhere):
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
As noted, they were removed from Firefox in version 59 (March 13, 2018)
I want to use an async function instead of returning a promise, however to reject I need to throw an error like this:
async function asyncOperation() {
throw new Error("Terminate this application.");
}
(async () => {
try {
await asyncOperation();
} catch (e) {
console.error(e);
}
console.log("Nope, I am still running!"); // This will be printed regardless
})();
This means that to catch the reject I must put the function call within a try statement. By doing this, instead of terminating the application, I catch the error and I can continue afterwards.
This of course works as you would expect however I want to throw an error to actually terminate the application regardless if the function was called within a try statement or not.
How could I achieve this without checking the error within the catch statement?
I want to throw an error to actually terminate the application
No. Throwing exceptions is done only to be able to catch and handle them. If you really wanted to terminate your application no matter what (which would be a bad, untestable design), you'd just call process.exit() and be done with it.
I might have other errors that I do want to catch.
It sounds like what you actually want is to handle some of the thrown errors but let those that are unhandled terminate the application as usually - unless caught and handled further up in the chain. For that, you'll want to conditionally re-throw the exception:
try {
…
throw Object.assign(new Error("…"), {reason: X});
…
} catch (e) {
if (e.reason == Y)
console.error(e);
else
throw e;
}
console.log("I won't run after X errors!");
Notice that none of this actually has to do with async/await.
Hey guys i wrote a code to raise exception ..The code is
<html>
<body>
<script>
var d =1;
try {
if(d == 2) {
console.log('fd');
}
} catch(e) {
console.log('catch');
}
</script>
</body>
</html>
When i give the value 2 for d the code inside try works but when the value is given 1 the code inside catch didnt works..
Can you tel me why its not working ??..Any help would be great ...Thanx
try...catch is for catching errors, not for handling conditional statements. if (d == 2) is perfectly valid and doesn't throw any errors, nor does the code within your conditional statement.
A catch clause contain statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch clause is skipped.
— MDN's Notes on try...catch
If you want to do something if d isn't equal to 2, you can use else:
if (d == 2) {
...
}
else {
...
}
If you really want to use a try...catch statement here then you're going to have to throw an error. You can do this with JavaScript's throw statement:
try {
if (d != 2) {
throw "d is not equal to 2!";
}
}
catch (e) {
...
}
The catch block here will catch the error, and the e argument will be equal to our error string: "d is not equal to 2!".
try/catch is for handling errors. You're not generating an error, since your comparison is a valid comparison. An error is not the same as an if statement that returns false.
That's not the way a catch is intended to be used. The catch block will be visited once an exception is thrown. As an example, try to add the following else block to your if:
else { throw new Error; }
That said, it is not a good idea to control your flow by means of exceptions and I strongly discourage the use of such a solution in a production environment.
You need to throws the exception. Use throw "Exception" inside code like this:
try {
if(d == 2) {
console.log('fd');
}else{
throw "Exception";
}
} catch(e) {
console.log('catch');
}
I would ask about java script error, is there type of error like php
or others,
example: In php we have notice, and Parse Error ..etc notice will not
be stop php execute, but parse will be stop execute php code
directly..
now is there js error like this, or what is the js classification
error .. I know we can handle error by try, catch ..,but is there
error in js was stooped script and others will not stop execute script
thank you
is there error in js was stooped script and others will not stop execute script
Not except for parsing/syntax errors, no.
JavaScript has exceptions. An exception exits the code in which it is thrown, and the code that called that, and so on until it's caught. If it isn't caught, then all currently-running functions are terminated and the error is logged to the web console.
So an exception (either one you throw explicitly or one that happens as a by-product of something you do) will either terminate all running functions (if not caught) or only terminate some code (if caught).
For example:
function foo() {
try {
bar(0);
}
catch (e) {
console.log("Caught exception");
}
}
function bar(a) {
if (a <= 0) {
throw new Error("'a' cannot be <= 0");
}
console.log("bar: a = " + a);
}
foo();
There, the code in bar following the exception is not run (we don't see "bar: a = 0") because an exception was throw, terminating bar. But foo's code continues, in the catch block, because foo caught the exception.
JavaScript is unusual in that you can throw anything, including a string, a number, etc. But if you want useful information, you usually throw Error:
throw new Error("Optional message here");
Since what you throw can be anything, you might be thinking there's a way to catch only certain things, but that's not the case. catch catches any exception that was thrown. So:
try {
throw "foo";
}
catch (e) {
}
try {
throw new Error();
}
catch (e)
}
try {
throw 42;
}
catch (e)
}
Note that those catch clauses are identical; they catch anything that was thrown. Of course, you can then inspect what you got and re-throw:
try {
// ...some code here that may throw any of several things...
}
catch (e)
if (typeof e === "string") {
// Handle it here
}
else {
throw e;
}
}
There we only handle exceptions that are strings, and not ones that are numbers, Error objects, etc.
You can create your own derived versions of Error if you like, although it's a bit more of a pain than it ought to be:
function MySpecificError(msg) {
this.message = msg;
try {
throw new Error();
}
catch (e) {
this.stack = e.stack;
}
}
MySpecificError.prototype = Object.create(Error.prototype);
MySpecificError.prototype.constructor = MySpecificError;
Then:
throw new MySpecificError("Something went wrong.");
Note that we had to fill in the code in MySpecificError to create the stack trace. (Also note that not all engines provide a stack trace, but if they do, this lets you use it.)
Some engines provide a few error types out of the box:
Error
RangeError (something was out of range)
ReferenceError (but usually that's something you'd let the engine throw)
TypeError (again)
SyntaxError (again)
Finally, it's worth noting that several things that would cause exceptions in other environments don't in JavaScript, mostly around math. For instance:
var result = 10 / 0;
In many non-JavaScript environments, that results in a runtime error (division by zero). In JavaScript, it doesn't; result gets the value Infinity.
Similarly:
var x = Number("I am not a number");
or
var x = parseInt("I am not a number", 10);
...doesn't throw a parsing error, it sets x to NaN ("not a number").
Yes. Javascript errors can have types, and there is a standard error type hierarchy. You can also write your code to "throw" things that are not error objects.
(In fact, since the catch clause in Javascript / ECMAScript does not discriminate based on the type of the exception, exception handling tends to be rather crude; i.e. "catch all errors" and then attempt to recover. Hence, to a first order, it doesn't matter what you throw.)
The ECMAScript 5.1 spec says that syntax errors are "early errors" and that they must be reported before the program is executed. An exception to this is syntax errors detected in code being run using eval. However, the spec doesn't say how early errors are to reported, or what happens afterwards. (At least, I don't think it does ...)
I believe that a common strategy for a Javascript parser/compiler/interpreter to skip to the enclosing block, and replace the affected code with code that throws an exception (e.g. SyntaxError) if it is run.
References:
http://www-archive.mozilla.org/js/language/js20-1999-02-18/error-recovery.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError
EcmaScript 5.1 - Errors
I am trying to test in browsermob if certain input field work or not. I am attempting to use a try...catch statement which I have never used before. I know that the form is:
try {
//some code
} catch (){
//some error code
};
What exactly is supposed to be put in the parenthesis after the catch statement?
When I try to use the statement it runs everything through the catch statement no matter if it is not an error. What am I doing wrong?
See the “try...catch statement” guide on MDN.
In short, try/catch is used to handle exceptions (which are "thrown" using the throw statement). The syntax for try/catch is:
try {
// Code
} catch (varName) { // Optional
// If exception thrown in try block,
// execute this block
} finally { // Optional
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
varName is available to the scope of the catch block only. It refers to the exception object which was thrown (which could be any type of object, e.g. a String, but is usually an Error object).
The try catch statement is used to detected for exceptions/errors that are raised inside the try-block. In the catch block you can then react on this exceptional behavior and try to resolve it or get to a safe state.
You got the statement almost right:
try {
// code that may fail with error/exception
} catch (e) { // e represents the exception/error object
// react
}
Consider the following examples:
try {
var x = parseInt("xxx");
if(isNaN(x)){
throw new Error("Not a number");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
try {
// some code
if(!condition){
throw new Error("Something went wrong!");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
the stuff inside try {...} is what you want to execute. The stuff in catch() { ... } is what you want to execute if you get any javascript errors from anything executed in the try {...}
catch {...} only executes if there is a javascript error in the try {...} block. You can find out what the error is by doing for example this:
try {
// do something
} catch (err) {
alert(err);
}
According to ECMAScript specifications,
try {
// Code
} catch (varName) { // optional if 'finally' block is present.
if (condition) { // eg. (varName instanceof URIError)
// Condition (Type) specific error handling
}
else {
// Generic error handling
}
} finally { // Optional if 'catch' block is present.
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
the code that is likely to throw an exception goes into try { }, The code to be run when an exception is thrown, comes into catch() { }. In catch() you can specify which exceptions you want to catch, and in which automatic variables to put it.
finally { } is always run, regardless whether exception was thrown or not.