6 Proven Methods For Handling Errors in JavaScript (promises, async, await, decorators, rxjs)!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey hey developers today I'm going to show you six examples of how to use JavaScript error handling in your applications so we're gonna look at promises we're gonna look at async/await we're gonna look at rxjs and custom decorators so if you don't know what the rxjs is don't worry I'll explain it but I'm gonna cover a lot of different types of error handling and so let's get into it [Music] hey and if you don't know my name is Eric I'm a full-stack software developer I'm also the author of UJS in action which I will make sure I put a link in the bottom and also if you click on that link and get signed up to my mailing list and I have I'll let you know when I have videos coming out and also I do really cool giveaways things like that so make sure you check that out in fact if you listen all the way to the end I might have something for you guys so stay tuned ok let's go ahead and start with promises and take a look at the error handling for that so if you don't know what promises I'll read the definition basically it's an object that may produce a single value sometime in the future either resolved value or in my reject so we use like commonly in many libraries that connect to do HTTP requests usually they have some kind of promise there's a lot of different scenarios you might use them we can go ahead and just create a fake one for now so we'll call it my promise and that's gonna equal new promise and then we usually have two things that go over out around with it we have a resolve and a reject like this by the way I'm just using es6 arrow functions to make things a little bit easier and then inside there I have a oops a arrow function and then from here we can do something so I'll go ahead put a set timeout and then inside the set timeout we'll have another arrow function which will then do something so we'll have it resolved first resolved it'll just return back a string and then we'll put in at time so it'll resolve in about one second so that should work it out that should clear all the errors here and yep no air so now we can use this promise and just take a look at how to normally work so if we wanted to take a look at this promise we just do my promise you can see we can either catch something or we can do use then so usually then is used when it gets resolved so we'll have a Val here and we'll just console.log the Val and you can see here it takes about a second and then we have resolved resolved there it is so it's working as we expect but if we have let's say this was rejected error and then we change this to a reject and rejects the bass second you could see here we did see the error for a second but that's because it was still resolving but now you can see here we're not getting anything because we're not catching it at all so the air is happening is just silently failing but we can use something called a dot catch and that will actually have my air in it and then once again I could just log that error right just to make sure I showed right I can do like this you see error that error so it's taking this promise and it's catching it and that's simply how you do it with inside this promises now I'm not going to get into this but one of the things that are disadvantages with promises is that a lot of times you need to take the value that gets returned from the promise and then you need to feed that in to another it's a promise of itself that you can then need to send somewhere else you a lot of times you get what's called a callback hell because you're having all these dot thenns cascading into each other and it becomes quite hard to read so here comes a sink await which can help with some of that so I'm gonna go ahead and just comment I'm gonna leave our promise so we're gonna use that same but I am going to comment out our example here and clear out our what we have here so the next thing we want to do is see if we can create a function and use something called async/await which will I'll show you here so so let's say we want we're going to test the promise and then this time bring you something called the async keyword and we're going to make sure we have something here and we can do I don't know if we can do far data and now we await the promise that we just kept that we just created and in that this case we'll go ahead and console.log the data now it's giving us an error because we promise that we have here is cannot find it so let's make sure we have it so we actually call it my promise so I'll make sure I call my promise here okay great and you can see here it's not doing anything because it's rejecting but if we change this to I don't know you say works we can then change this to resolve see if it takes a second it's a resolving make sure it waits correctly oh and we'll of course we have to run it so we'll just run it like this I'll take a second cool so we can see our normal works right here so one thing we can do if we have an air so we'll change it back to reject error is we can take this data which is in this block here and we could surround it by a try-catch which sort of looks like this and then we have a catch here with an air and then what we do is we take our promise we surround it inside the try block and then inside the air block which I can by the way I'm using very very here but that's fine and then I inside the catch block I can console I guess we can do console dot error error and you see here now we got the error back so that's this Eric here just reject hi I got error you see in console we got hide out air so we know it's now catching it which is perfect now the problem with the try catch block is it's a little verbose and you have to put this try catch block after every single every single time you do a wait you're gonna have to try to catch it so there there is a better way to do it and this is yeah so this definitely doesn't make it this a wait async await is really great-looking but when you start come when you start having to put in these try catch blocks it becomes not so perfect so one thing we can do and I'll go ahead and go to our next example is we can create something called a function or a error handler factory using what's called a high order function so we can have the same example here so I'll copy this with our test promise and our weight and our closing this time we'll just close it but we won't use a try/catch block and I'll uncomment this and we'll use our test promise here and obviously see nothing showing up in our console law because we're not catching the error at all but what we could do is create kind of this high order function that will basically this function Factory which return basically we will send it a function it'll attach the dot catch to it and it'll return that function back to us so let's take a look how that would work here so the easiest way to do that is we'll create another function here so we'll call we're just call HOF high order function well we'll call it error handler I don't know we call wrapper and we'll have a function and I'll go ahead and switch this to es6 in a second but this might be easy to understand at first we have a function that accepts a function and it's gonna return another function which will by the way we can do these three dots and put in parameters or prams or whatever you want and this will make sure that we get all the parameters that are coming through parameters and then this will return this will return basically the the function that we want to return here so it's in return the FN but this time we're going to do the dot catch on it and this time we'll defend a catch we'll also have like function which once again will return well this time we won't even return anything we'll just console.log the error so this is gonna be our R so this is our error handler just kind of verbose just putting the functions in so we had this error handler except in a function as a parameter it then returns a function that this dot parameters is everything that was passed into it we're going to use the function here and add a catch to it so basically we're turning that function with the dot catch which is going to just log out the air so let's see if that works so our test promise didn't work but if we now put it in the error handler and now we run it like this oops I got to do this dot dot parameters there it is so now we have I'll go ahead and run that again so now we have this high error so what it's doing is it's it's attaching this parameters this function parameters it's attaching that catch and then returning it so that way it works however if we it shouldn't if we change this back to resolve hi working and we reloaded here see right here we don't have anything happening if it fails but we keep it consul or if it doesn't fail so we constantly data here so it's working so this is working but if we change this to a reject hi not working and we put this to eject see hi not working so cool now this is pretty verbose right here we're passing in we're returning the function catching it but we can rewrite this in kind of an es6 style so instead doing this way we can do const error handler and diller and from there we can pass in the function will do error functions here and that's gonna pass in the parameters we're gonna return the parameters which will then run here parameters we're gonna then add the dot catch to it we're gonna do the air and then we're gonna console.log the I should probably console warn or air but ER air and cool so if we run it again you can see your hair air hi not working so it's returning it's rejecting it with the hi not working and we're adding the text er R to the front of it so that's it that's how you could do it you can also probably do custom error handling you could pass in more values into your function that gets passed into the air handler but for now we'll just leave this as is so that's that's like a one-liner way of doing this this custom air handler so what you do is every time you have a function in your app that needs to be executed you can wrap it in this air handler and that way if there is any errors that it gets sent somewhere if you're like for example on node you can then run it on next and you can then send it to your custom error handler a node or show up on the page or something so that is one way to do it and what I'll do by the way is this all this code will be on stack Blitz I'll put a link in the description below so you guys can test it out and play with it at the same time see what I'm doing alright so now we're going and moving on to rxjs so rxjs just brill briefly for not familiar with it it's a type of technology it's really familiar with angular developers because it's really built-in to angular 2 plus and it's a way you can take and you can instead of using promises you everything is a stream and you have all these rxjs operators that you can use to do a lot of things you can add delays you can map things you can switch map things you can you can do a lot of really cool things so I was just going to show you guys how you can use rxjs to to go ahead and create to catch an error in something so the easiest way we can do that then to start off with is to take the promise that we have already and then converted over to a observable so we can use it inside our inside what we're trying to do here so to do that I'm going to create a new observable I'm going to use this from operator and we're gonna pass in to my promise and you can see here at the top I went ahead and imported in these imports of pipe from so from is a way and by the way I have typescript on this as well but I'm not going to use too much typescript until the end so from is a rxjs operator that we can convert either arrays or promises to observables so this now new observable can be observed which is cool so now if you look at the observable we can then you can see we have a subscribe we can subscribe to it and what will happen is is it will return back the value if it for example it just resolved without any problems it would return a value through your subscribe so we can see that that looks like console.log odds and we'll just pass into Val you see right now I don't get it it doesn't work but once again if I go back up here and just just anxious to resolve hi working you see OBS hi working so you see it's working right there so we know that the SUBSCRIBE is working but we want to look at errors so we'll put it back to reject hi not working and you see that's not showing up in the console because it's not working we don't have any way to to handle it so what we can do with this observable is we can use the pipe operator and with the pipe operator is a way we can pipe in operators into rxjs and the one you would want to use for this is called catch air and the catch air is basically accepts an error here and then it returns for the catch air it returns an observable so there's this operator called Oh F that we can then return an operator so we could say I don't know error and then we can pass in this error here oh so we have this catch error here inside the catch air will have a Val which will then equal here why shall we'll do this we just have a written wrong so with the air here there it is now it's giving us error about the subscribe because grabs an ID is this type operator function so we'll have one more thing like this so on a more ending class so there we go so we have OBS air high error not working so if we do this and it takes a second so now we're catching the air so the new observable we do this catch air we have air here we're piping it - Oh F which is right here I subscribed in basically it creates some observable from like a text string and then we're just returning a string and then that way this will be shown soon as the error occurs so it rejected so we have this error now there is a way so that's how you do with rxjs just a basic catch error so what we can do here is instead of catching it we'll go ahead and create a custom error handler which is really easy so to do that to create the custom error handler I'm going to call Const I'm gonna call it custom error handler operator doesn't matter what I call it really and from there I'm going to send a message with it I'll show you guys how that works and then I'll have this catch error which is that rxjs operator and once again we'll have the air here and we'll do the Arab functions so this might look familiar what we just wrote we'll put in the message and then we'll put in the vowel here so oops I mean the ER yeah so what this does what this is saying is that this custom error handler we're going to take we have a message that's passed into it it's going to send it to the catch air and it's going to display it on the screen so now if we go back let's I'll go ahead and copy and paste this for the sake of time and we're going to still have a new observable we're gonna have the new observable here but instead of this piping the Quechan we're gonna pipe in this custom error handler operator and then we're gonna pass in a value to it which will be hi test one two three and you can see down right here it's working I'll just go and refresh it so now I piped in a message obs test one two three hi not working so it's passing in this OBS here and the test one two three is getting concatenated with it so it's even though it's the custom air handler is failing it still subscribes right here so we still get the message even though it failed because we have this this error handler in there so the way it works is we have this custom error handler and then we have the pipe and we're having our own custom error handler and then it's still hitting the subscribe and then displaying it down here so that's how it's working all right so we have one more that I'll show you and that is how to use like a decorator so we're going to create this most simplest class here I'm going to do class my class and then inside there I'm gonna have a async function which is going to be called my funk and that is going to Kant's test and that's going to wait my promise that we created earlier and then I'm going to console.log test and then underneath here I'm going to Const a test class which will be new my class and then I'm going to run test class dot my func my function which you can see right here I don't have anything on the screen because it is failing so what we can do is create something called a decorator now a decorator is like a structural design pattern that lets you attach new behaviors to objects by placing them inside wrapper objects so we would do something like this we would have that catch here which this @ sign signifies when you're using typescript with classes that you're creating a decorator and you can see here decorators you would have a target a key and a descriptor so now we need to implement this at catch so that way when we in this instance that actually something happens so if we go all the way back up to the top we have this catch and I already created a directory or full file for called decorator so if I go to the decorator class I kind of started it off and we have this this idea of a of a catch we have a target key in descriptor target it depends on where you're using the decorator if you're using a method these actual values are different than if you were let's say using it on on something else like a like a class or a property so what I can do first of all Kant's will go will create original method which descriptor basically we can grab the descriptor value so this is the original method method and then what we're gonna do is we're gonna overwrite it with a different type of message so we're gonna do the descriptor dot value we're gonna do an async function here and we're going to use a function and we're gonna describe to args from it function dot dot dot args and then inside here we'll do our try catch block and so first we're going to return we're going to wait we're going to take the original method method here and we'll apply this and args so what we're saying right now is that we're just going to return the Zac's a method if it doesn't have any problems however if there is an error that's where this catch comes in handy we're going to console.log what we'll do air doesn't matter an error the actual error itself and then right before here we'll return it's the script or so it's kind of we call it a functor e because it's actually returning back a function so that should be it will save it here and then we'll just add a space here so original methods not defined Ridge and now original I got a typo here let's try that again cool so you see hi not working so it's taking the it's passing it's doing the try catch and it's sending back the air so we go back here I'll save it go back to index dot H team and XTS so now our class with this decorator is the airs so that way we are good to go and we can add this at catch to every single method inside any of the classes we want and every time we have an error it will then log to our error right here and we can all do we can do all sorts of fun things we can actually pass values in here if we wanted to so we can have like custom error handlers if we really wanted to but I we're not gonna do that right now because it's a little beyond the scope so there there it is that was six different examples of different ways you can do error handling in JavaScript I know the last two rxjs and the decorators we went over quickly but if you guys are interested make sure to look at the stack bliss I'll make sure I put a link in the description so you guys can play around that all be commented out so just makes you uncomment it make sure you go and comment the promise at the top and then you can try each one of the examples and see how it all works really appreciate you guys watching leave a comment to have any questions below thanks
Info
Channel: Program With Erik
Views: 4,347
Rating: 4.7714286 out of 5
Keywords: Javascript errors, javascript error handling, try catch Javascript, rxjs catchError, How to create custom decorators, TypeScript decorators, async await, error handler, Javascript functions, javascript promises, Promises javascript, How to create a promise, How to catch an error in a promise, rxjs operators, custom rxjs operators, Program With Eric, Program With Erik, Erik Hanchett
Id: LrGvvvmRkCE
Channel Id: undefined
Length: 27min 0sec (1620 seconds)
Published: Wed May 08 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.