NestJS Crash Course 02 | Exception Filters, Validation Pipes and Custom Decorators

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys in this video I'm going to show you some examples of exception filters validation pipes and custom decorators for the exception filters we are going to create a single strategy manage application exceptions within a filter class and a decorator to apply that strategy for the validation pipes we are going to create a validation class for a tto and we are going to also use a decorator to make that work finally we are going to create a custom decorator for our video and we're gonna see how to use that in our API and if you wanted to blow your applications in a relay of global infrastructure with a product on pricing check out the node there is a link in the description below this video remember to Like share and subscribe to the channel and it's good stuff the nastiest exception filters can be applied using a decorator in the method or in a controller or we can normally apply a filter by declaring it in our main TS file let's jump into PS code and let's see how we can use exception filters on a previous video we created our shops controller basically here we define all the different end points of our API we defined that again and point post code and activity and point them let's execute the post endpoint for example so let's create a new job and let's pass C++ developer as the title as a salary will pass 7,000 so let's run this and okay so now we created in our body B and you developer so if we go to the MongoDB database we're gonna see that we can access that document here in the jobs database we have a document C++ developer and the salary has thousand okay and so let's go back let's grab this identifier and this identifier we can go to the API and we can get the shop information okay but what happens if we change the identifier let's put something random here and we send a request so we get we still get a 200 response and that's not correct for restful api because we want to receive in this case when we don't get any results we're gonna get a 404 or an HTTP and not far so let's make a change in our get endpoint let's go back to our controller and let's make a change here in our get endpoint so we can return and attp status according to the result so if we don't get any results from the database we need to return and not found HTTP response a follow for so here what we need to do is we need to handle these promise so we are going to add and then here and I'm going to create another function to handle this promise response [Music] where I'm going to receive a result and what I want to do here is if I get a result I'm going to return that result but if we don't get any results I want to throw an exception so this will allow us to see how nest jeaious handles to be exceptions by default and then we are going to create our exception filter and we're going to see the difference between the two strategies the nastiest default strategy and the free third strategy with the class that we are going to create so now what we are going to do here is I'm going to throw an exception throw new exception and I'm going to pass a message I'm going to pass the HTTP status and I'm going to return the HTTP status as the found actually the it should be called is 404 and I'm going to also add a catch block here I'm going to be done or another error function for this and here I'm going to throw the same exception okay let's try this now and now we send the request and we receive up 404 as we expected and the message that with just enter there okay so this is the default behavior of n'est pas and now I am going to create a filter and I'm going to centralize the exception management using that filter and first I'm going to grab this code from their nest say yes documentation and I'm going to optimize this filter a little bit I'm going to create a new folder this is going to be keep doors and I'm going to create a new file that's going to be HTTP exception that filter that yes and here I'm going to paste the code type that I grabbed found the nest yes the imitation website okay basically what is doing here is implementing the exception filter interface with this HTTP exception filter is using this catch decorator with this HTTP exception as a parameter so is going to catch all the HTTP exceptions depending on the scope that we define we're going to see that in a second and here one is doing is is extracting the response the request is extracting the status code from the exception and is generating this response including the status code and chasin with the status code a timestamp a path and we can add whatever we want or something like that okay and now what we can do with this filter this HTTP exception filter that we are going to import into the controller now and here we can apply this filter at a method level or at a controller level and in order to do that we can use in a specific decorator that is called use filters wherever we can pass a list of filters in this case remove the bus just this one we can pass it in two ways if we just pass the class name as it is now the framework is going to inject using the dependency injection mechanism as we recheck the instance of this filter the instance of this class or we can create the instance ourselves like this and going to work either way so let's just put the class name so on Astraeus is going to inject an instance for us okay let's try this now let's go back to postman and let's execute this request on a random with a runner identifier that we know that is not in the database so if I execute this request now I get the custom jason that i define it on the filter as we can see here that we have a status code a time stamp a path and a description is a fiction HT peter so that's one way of specifying the or applying the filter right at the method level we can also apply the same filter I'm going to grab this and move it at the controller scope if we throw an exception in any of these endpoints is going to apply this is filter at the controller level so let's try this now and if we go back and if you run this we should get the same response yes we get the same response as before and if we remove this completely we can include that exception filter globally in our main file so I'm going to grab this and I'm going to paste it here I'm going to port this filter here in our main TS file I'm going to change the path and what I can do here is I can do app that use global filters and hearing a pass a list of filters in this case I'm going to pass this only this filter and here is I'm here I need to create an instance of it okay let's go now and let's execute a request again and we're gonna get the same result so we apply it this filter at a method level then we apply the same creature using the decorator at a controller level and finally we created or we apply this filter globally nest jellies validation pipes we can apply validation pipes using a decorator or in a parameter and method or in a controller or we can globally apply a validation pipe declaring it in our main PS file let's shine into be a scope and let's see an example of a relation pipe okay now let's create a validation pipe so as you may remember nest sheis allow us to use DT O's to encapsulate the body that we receive as part of the requests in our endpoints for example in our post endpoint so what we're going to do first and we do stop the server and I'm going to install a couple of dependencies so I'm going to run npm install save plus body late for class okay and the first thing that I need to do here let's run so again I'm going to the DTO and what I'm going to do here is I'm going to import the class validator library report plus one later and I'm going to pour a couple of decorators his string and this int and I'm going to use these decorators here string and using these decorators I'm going to be able to validate the the input but another thing that I need to up is the actual pipe so I'm going to create a new folder let's call it pipes and I'm going to grab the validation pipe from the nest Shreyas website we also have the authority to use joy joy is another library in this case we're going to use class validator okay and this is the validation pipe that I want I want to use so let's create a new find here let's call it validation that five that PS and that's pain code and this is going to implement the pipe transform interface and it's going to make some mendacious is going to make some transformations here I need to I'm going to change this to any so we don't get any curse okay so let's go back to our controller and hear what we can do is we can apply this is pretty similar to the filters where we can apply the validation pipe at a method level a controller level at global level and also at a parameter level so we can actually add a little here so that's gonna be the first thing that we're going to test we can add and validate it's the we can use the validation pipe this and we report it first actually pipe validation that file and here we are going to validate this shop DTO at the param level so let's go back to both man and let's execute a post request but instead of passing on a number and the job will be to pass and string here so we should get an error yeah we get the HTTP error remember that we still have running here in our main that PS file we still have this exception filter so we can do something different here if we go back to the pipe we're gonna see that what we are throwing here is about the requested exception so we can copy this exception listen up this is not a good practice just for the sake of giving an example of this I'm going to program based of course we need to create a superclass we need to extend it we need to try to don't repeat ourselves but just for the sake of example I'm going to copy and paste this I'm going to rename this and I'm going to call it validation exception filter that yes and here I'm going to catch this by the request exception and let's make a couple of changes here as we import this ok here we can say bad request let's say this and now if we go back to be main that PS file we can use that filter so let's import it this bad let's grab it from here I am actually I'm going to change I'm going to name this one too by deviation filter or validation exception filter that's going to be better and I'm going to import that here validation exception filter and to change this this is going to be validation exception data filter and I'm going to use this one okay now if we go back to postman and we execute the same request we should get a different description from this and we get the description that we specified for that exception specifically so in this case we are using two things we are using this validate on this validation type and we are using also validation exception filter and if we go back to the controller we can also define this validator or we can apply this validator at a method level we can say sorry this is use pipes and we can pass sorry the validation pipe actually yeah so if we execute the request again we should get the same response yes we get about requests and we get the description that we specified on the filter for the validation exceptions and we can also use pipes at the controller level so let's do that and let's go back to both man and let's run this again and we're gonna get the same same response if we remove this from here let's say this I'm going to grab the values of pipe and I'm going to include this validation pipe globally in our main that PS file I'm going to change the path in I'm gonna use here app that use global pipes and I'm going to include in the name of the pipe I need to create a new instance of the validation pipe actually but in pipe and now if we go back to postman and if we run the same request we should get the same response nest Reyes custom decorators we can create a custom decorator to be more specific regarding the requests that we receive in our endpoints and custom liberators will allow us to improve the code readability of our application is going to put their visibility and we come to apply pipes on these custom decorators for example a validation pipe or we can also access a particular property from our custom they create a custom decorator panel should be useful if we need to pass the data of an authenticated user in multiple endpoints so let's go to this code and let's create a custom decorator for our API okay and now let's create a custom decorator so I'm going to create a new folder decorators and I'm going to create a new file I'm going to call this show data that decorator that PS am here what I'm going to do is I'm going to import a function the function is create [Music] industries come on already [Music] okay and here what I'm going to do is I'm going to create constant data and I'm going to use that function to create my custom decorator the idea is to use this decorator instead of you physically using body in here let's go back to controller so instead of using at body as the decorator I want to use at shop data so it's not that is not just a generic bodies and a specific request that I'm going to describe there right I'm going to describe this show tto data so let's go back to be the greater and here is going to this function is going to receive an arrow function what I am going to receive that data I'm going to see a data argument it's going to be a string and then the request and here what I'm going to do is I'm going to return if I get data I'm going to return the body of the request and we draw the condition here to check that I will see the data break that body theta and in the other case I'm going to return the body completely okay let's go back to the controller and I'm going to import that custom decorator so the graters should be that that the grater and now I can use that the collector here for example and now I should be able to create a new job as usual so that's a Java developer 8,000 let's run this and I am able to create it and we still have our validation pipe and our validation exception filter right so if I pass this a stream I should get an hour yes again the same error as before so still running I'm going to command this and I'm going to apply this validation pipe at this level at the param level so I can pass it here and if I run this request again I should get the same error yep I get the error but I'm not rapping I mean I'm not using the customer exception so I'm going to add exception here so I'm going to use the filter goose feeders and I'm going to bus the let me go back to the main that yes this one by the Dacian exception filter I'm going to pass that one okay I think I have to import it okay this from here let's let's paste it here let's paste it here and change the path yes like that okay and now we should get the error and we should get the JSON that we specified here with this budget request in the description so let's go back to postman and let's run this again and yes we get the Chasen that we specified on that validation exception filter so if we go back to let me close a living here so if we go back to the controller to the shops controller here we are using a custom decorator with a validation pipe and we are also using the validation filter or the exception filter here at the method level so that's all I have for today thank you guys for watching remember to like and subscribe to the channel and I see you guys in the next one Tigger bye [Music]
Info
Channel: Pragmatic Reviews
Views: 10,277
Rating: undefined out of 5
Keywords: nest crash course, nest js, nestjs, nest tutorial, nestjs tutorial, nest js tutorial, nest rest api, learn nest, javascript, nestjs course, nest course, nestjs mongodb, nestjs typescript, nest pipes filters decorators
Id: nK6SpFIEvtQ
Channel Id: undefined
Length: 31min 14sec (1874 seconds)
Published: Sat Dec 21 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.