/    Sign up×
Community /Pin to ProfileBookmark

error handling

I just finished codecademy’s javascript course and have also finished a couple of personal side projects along the way to help reinforce some of what I’ve learned. Now, I’m trying to fill in some gaps that the course leaves out, and that led me to this question on testdome.

“Implement the ensure function so that it throws an error if called without arguments or an argument is undefined. Otherwise it should return the given value.”

[CODE]function ensure(value) {

}[/CODE]

This was my first attempt.

[CODE]function ensure(value) {
if (value == null) {
return “error”;
}
else {
return value;
}
}[/CODE]

This passed one of the three criteria, but it’s failing for not returning the correct value if there is no argument or if it’s undefined. After more research, I saw try/catch as a possible solution, but that was not covered in codecademy and my new attempts have even been less successful. I understand the w3schools examples, but I’m failing to fully understand how to apply it in a general real world sense. Before I get too far ahead of myself, though, am I even going down the right path? Or is there something I should be looking towards besides try/catch? Thanks!

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@smatchymoauthorApr 30.2017 — Rereading the question, I'm pretty sure I need to use try/catch. This part seems pretty telling, "throws an error." Here's one example of what I've tried.

[CODE]function ensure(value) {
try {
if(value == null) throw "my error";
return value;
}
catch(err) {
return err;
}
}[/CODE]


This seems to work in all of my test examples. Here I've substituted return with console.log for better visibility. I don't know if I'm supposed to have a code that would throw "my error" if there was no variable train anywhere. Train is undefined, though, so I feel like I've provided something that should actually satisfy all three criteria, but this still only satisfies one of three.

[CODE]var train;
function ensure(value) {
try {
if(value == null) throw "my error";
console.log(value);
}
catch(err) {
console.log(err);
}
}

ensure(1);
ensure();
ensure(train);[/CODE]
Copy linkTweet thisAlerts:
@xenoraphorzeApr 30.2017 — An issue I see is you are still checking for the value of value which IS an argument how are are you going to throw a error when there are no arguments. The other thing that is unclear is they say:

Otherwise it should return the given value.[/quote]

First thing to check is the documentation (hey!) for the javascript arguments object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

here they show an example of something like.
[code=php]
var args = Array.from(arguments);
var args = [...arguments];
[/code]


To get your arguments object. So with this we need to ensure function so that it throws an error if called without arguments[/quote]

so Throw: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

and Error: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

From this knowledge we could craft something like.

[code=php]
function isArgs(args) {
if (args.length > 0) { return true; }
throw new Error('function Ensure expects an argument value', 'randomFile', '666');
}

function checkAll(args) {
isArgs(args);
args.forEach((arg) => {
const argType = typeof (arg);
if (argType === 'undefined' || arg === null) {
throw new Error('invalid input', 'randomFile', '666');
}
});
}

function ensure(...args) {
checkAll(args);
return args[0];
/* not sure if they want all values here or just the first value
* you can change this to return ...args to return an array of values if they passed multiple
* ie: return args;
* The directions are unclear on this part.
*/

}
[/code]
Copy linkTweet thisAlerts:
@smatchymoauthorApr 30.2017 — An issue I see is you are still checking for the value of value which IS an argument how are are you going to throw a error when there are no arguments. The other thing that is unclear is they say:



First thing to check is the documentation (hey!) for the javascript arguments object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

here they show an example of something like.
[code=php]
var args = Array.from(arguments);
var args = [...arguments];
[/code]


To get your arguments object. So with this we need to

so Throw: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

and Error: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

From this knowledge we could craft something like.

[code=php]
function isArgs(args) {
if (args.length > 0) { return true; }
throw new Error('function Ensure expects an argument value', 'randomFile', '666');
}

function checkAll(args) {
isArgs(args);
args.forEach((arg) => {
const argType = typeof (arg);
if (argType === 'undefined' || arg === null) {
throw new Error('invalid input', 'randomFile', '666');
}
});
}

function ensure(...args) {
checkAll(args);
return args[0];
/* not sure if they want all values here or just the first value
* you can change this to return ...args to return an array of values if they passed multiple
* ie: return args;
* The directions are unclear on this part.
*/

}
[/code]
[/QUOTE]


Here is a quote from W3schools, "Function arguments are the real values passed to (and received by) the function."

https://www.w3schools.com/js/js_function_parameters.asp

Since the starter code provided by testdome is:

[CODE]function ensure(value) {

}[/CODE]


I think it's pretty safe to assume that all we're worried about is "value" from calling ensure(value); They want to throw an error if value is undefined, or not provided. When it is provided and defined, the ensure function should return the value provided instead of an error. The answer should actually be very straightforward. They had one question where 10 mins were allotted and it wasn't a problem at all. This one has 3 mins allotted and is proving to be quite the pickle for me. For example, here is the 10 min question along with the starter code provided by testdome:

"Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.

For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API."

[CODE]function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
}

console.log(formatDate("12/31/2014"));[/CODE]


Here was the answer which fit neatly in the starter code provided.

[CODE]function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var date = userDate.split("/");
var month = date[0];
var day = date[1];

if (month.length === 1) {
month = 0 + month;
}
else {
month = month;
}
if (day.length === 1) {
day = 0 + day;
}
else {
day = day;
}
return date[2].concat(month, day);
}

console.log(formatDate("12/31/2014"));[/CODE]
Copy linkTweet thisAlerts:
@rootApr 30.2017 — If you are handling errors, you only need to implement the [B]try{}catch(e){}[/B] handler to allow you to deal with errors internally without causing the browser to produce a stream of errors.
Copy linkTweet thisAlerts:
@ZorgMay 10.2017 — You can try this.
[code=html]
<script>
var value = 'some value', check1, check2;

function ensure(value) {
if (value === undefined) {
throw new Error('Value is not defined');
} else if (value === null) {
throw new Error('Value is null');
}

return value;
}

check1 = ensure(value);
console.log(check1);

check2 = ensure();
console.log(check2); // won't reach here, error is thrown
</script>
[/code]
Copy linkTweet thisAlerts:
@kirankumarrrJul 04.2018 — --> Below code will work properly

function ensure(value){

if(typeof value == "undefined" ){

throw "my error";

}

else{

return value;

}

}

or

function ensure(value){

if(typeof value === "undefined" ){

throw "my error";

}

else{

return value;

}

}
Copy linkTweet thisAlerts:
@rootJul 04.2018 — {"locked":true}
Copy linkTweet thisAlerts:
@rootJul 04.2018 — @kirankumarrr#1593548 PLEASE DO NOT RESURRECT OLD POSTS,

It may be from 2017 but in terms of internet, a very old post.
×

Success!

Help @smatchymo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...