Hello everyone,
It has been awhile since my last post, but let me assure you I have been busy. Recently, I have been working on making a game, which when I finish, I will show you guys. For one of the modules, the program must report an error. I was using console.error(‘message’), but I also know of the try{}, catch{}, and throw method too. Is one better than the other? The console.error looks better for just running a single string.
Thank you all,
They are all different things and have different use cases.
try{} catch{}
will catch synchronous errors e.g. type error
or async errors (reject) inside an async function
with await
but not async errors while wrapping around Promise.then()
.catch()
will catch Promise.reject()
and standard errors inside a Promise.then().catch()
block but not standard errors in await runFunc().catch()
throw
will create an error to be caught by the calling function or code with the first catch{}
and will terminate the following code or program.
console.error()
doesn’t catch anything
throw
is a self defined error so you probably want use it only to terminate the function for things that are not errors for example fetch() returns 404
Promise.catch() 404 example
const get = function(url){
fetch(url)
.then(res => {if (!res.ok){throw 'error: 404'}; else{return res}})
.then(res => res.json())
.catch(err => console.error(err))
}
async await try{} catch{} 404 example
const get = async function(url){
try{ let response = await fetch(url);
if(!response.ok) throw 'error: 404';
let json = response.json()
return json}
catch(error){console.error(error)}
}
I tend to use return new Error() e.g.
const get = async function (url, options = {method: 'GET'}){
let response = await fetch(url, options);
if(!response.ok) return new Error(`fetch error: ${response.status}`);
return response
}
const caller = async function(url){
try{
const res = await get(url);
run some more code();
}
catch(err){console.log(error) ;errorFunc()}
}
So to sum it up use try{} catch{}
for async await
, .catch()
for Promise.then()
, throw
to terminate regardless of catch block and return new Error()
to pass the error onto the caller to be dealt with. finally{}
blocks are also pretty handy.