Created
August 22, 2020 08:19
-
-
Save alperencapar/24eb7fef6651a00a0bb7ffe7e4251d7c to your computer and use it in GitHub Desktop.
Javascript ES7 Async Await Error Handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Request{ | |
| //HTTP response status codes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status | |
| async delete(url){ | |
| const deleteResponse = await fetch(url,{ | |
| method: "DELETE" | |
| })//Continues only after the promise has resolved | |
| //Since our method is deleting data | |
| //there's no need to return json or text object response from where we make the function call | |
| // const responseText = await deleteResponse.json(); | |
| // return responseText; | |
| //declaration that we're erased the data is enough | |
| if(deleteResponse.status === 200){ | |
| return "Data Deletion Successful"; //returns a promise | |
| } | |
| else if (deleteResponse.status >= 400 && deleteResponse.status < 500){ | |
| throw new Error("The server could not understand the request due to invalid syntax!"); | |
| } | |
| else if (deleteResponse.status >= 500 && deleteResponse.status < 600){ | |
| throw new Error("Server Error Has Occurred !"); | |
| } | |
| else{ | |
| throw new Error("An Error Occurred! Error type is unknown"); | |
| } | |
| } | |
| } | |
| const request = new Request(); | |
| //calling delete function | |
| request.delete("https://jsonplaceholder.typicode.com/albums/9") | |
| .then((result) => console.log(result)) | |
| .catch((err) => console.error(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment