Common Errors in JS and from Rest API
Sraban Pahadasingh June 25, 2024 01:49 AMIn JavaScript, errors can be categorized into different types, including logical errors, runtime errors, and syntax errors. Logical errors occur when the code does not behave as intended, often due to a mistake in the code logic. There are many other common errors that you might encounter or need to handle in JavaScript.
List of JS Errors:
1. Division by Zero
- Description: Attempting to divide a number by zero, which is mathematically undefined. In JavaScript, this results in
Infinity
for positive numbers and-Infinity
for negative numbers. -
Example:
let result = 10 / 0; // Result is Infinity
2. Null or Undefined Reference
- Description: Trying to access a property or call a method on
null
orundefined
. -
Example:
let obj = null; console.log(obj.property); // Throws TypeError: Cannot read property 'property' of null
3. NaN (Not a Number)
- Description: Using a mathematical operation that does not produce a meaningful number, resulting in
NaN
. -
Example:
let result = "string" / 2; // Result is NaN
4. Array Out of Bounds
- Description: Accessing an array element with an index that is outside the array's range.
-
Example:
let array = [1, 2, 3]; console.log(array[5]); // Result is undefined
5. Invalid JSON Parsing
- Description: Attempting to parse a string as JSON when it is not properly formatted.
-
Example:
let jsonString = "{ invalid JSON }"; JSON.parse(jsonString); // Throws SyntaxError: Unexpected token i in JSON at position 2
6. Division by Zero in Modulo Operation
- Description: Using zero as the divisor in a modulo operation.
-
Example:
let result = 10 % 0; // Result is NaN
7. Negative Square Root
- Description: Calculating the square root of a negative number, which is not a real number in real number space.
-
Example:
let result = Math.sqrt(-1); // Result is NaN
8. Exponential Overflow
- Description: Exceeding the upper limit of the number range that JavaScript can handle.
-
Example:
let result = Math.pow(10, 1000); // Result is Infinity
9. Function Argument Count Mismatch
- Description: Passing an incorrect number of arguments to a function, which can lead to unexpected results.
-
Example:
function add(a, b) { return a + b; } let result = add(1); // Result is NaN because b is undefined
10. Circular JSON Structure
- Description: Attempting to stringify an object with circular references, which is not possible.
-
Example:
let obj = {}; obj.self = obj; JSON.stringify(obj); // Throws TypeError: Converting circular structure to JSON
11. Array Length Modification
- Description: Changing the length of an array manually can cause truncation or add undefined elements.
-
Example:
let array = [1, 2, 3]; array.length = 5; console.log(array); // Result is [1, 2, 3, undefined, undefined]
12. Invalid Function Constructor
- Description: Passing incorrect or malicious code to the
Function
constructor. -
Example:
let func = new Function('console.log("hello'); // Throws SyntaxError: Unexpected end of input
13. Range Error
- Description: Using a number outside the allowable range for a specific function.
-
Example:
let result = new Array(-1); // Throws RangeError: Invalid array length
14. Type Error
- Description: Performing an operation on a value that is not of the expected type.
-
Example:
let num = 123; num.toUpperCase(); // Throws TypeError: num.toUpperCase is not a function
15. Stack Overflow
- Description: Caused by excessive recursion, leading to the call stack exceeding its limit.
-
Example:
function recursive() { recursive(); } recursive(); // Throws RangeError: Maximum call stack size exceeded
16. Invalid Array Index
- Description: Using a non-integer or negative index to access an array element.
-
Example:
let array = [1, 2, 3]; console.log(array[-1]); // Result is undefined
17. Invalid Date
- Description: Creating a
Date
object with invalid date values. -
Example:
let date = new Date('invalid date'); // Result is Invalid Date
Conclusion
Understanding these common errors can help you write more robust JavaScript code and handle edge cases effectively. Proper error handling and validation can prevent many of these issues from occurring, improving both the stability and user experience of your applications.
List of Rest API Errors
REST API errors can occur due to various reasons ranging from client errors to server issues. Properly handling and returning meaningful error responses in a REST API can significantly improve the developer experience and make debugging easier. Here’s a list of common REST API errors along with descriptions and examples.
1. 400 Bad Request
- Description: The server cannot process the request due to client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
-
Example:
{ "error": "Bad Request", "message": "Invalid JSON format in request body." }
2. 401 Unauthorized
- Description: The client must authenticate itself to get the requested response. This is typically used when authentication is required and has failed or has not yet been provided.
-
Example:
{ "error": "Unauthorized", "message": "Authentication is required to access this resource." }
3. 403 Forbidden
- Description: The server understands the request but refuses to authorize it. This status is used when the client does not have the necessary permissions for the resource.
-
Example:
{ "error": "Forbidden", "message": "You do not have permission to access this resource." }
4. 404 Not Found
- Description: The server cannot find the requested resource. This status is typically used when the endpoint is valid but the resource itself does not exist.
-
Example:
{ "error": "Not Found", "message": "The requested resource could not be found." }
5. 405 Method Not Allowed
- Description: The request method is not supported for the requested resource. For example, an API might support
GET
but notPOST
for a specific endpoint. -
Example:
{ "error": "Method Not Allowed", "message": "The requested HTTP method is not allowed for this endpoint." }
6. 406 Not Acceptable
- Description: The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.
-
Example:
{ "error": "Not Acceptable", "message": "The requested content type is not supported by this resource." }
7. 409 Conflict
- Description: The request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.
-
Example:
{ "error": "Conflict", "message": "The request could not be completed due to a conflict with the current state of the resource." }
8. 410 Gone
- Description: The requested resource is no longer available and has been permanently removed.
-
Example:
{ "error": "Gone", "message": "The requested resource is no longer available and will not be available again." }
9. 415 Unsupported Media Type
- Description: The request entity has a media type which the server or resource does not support. For example, the client uploads an image in a format not supported by the server.
-
Example:
{ "error": "Unsupported Media Type", "message": "The requested media type is not supported." }
10. 422 Unprocessable Entity
- Description: The request was well-formed but was unable to be followed due to semantic errors. This is commonly used for validation errors in APIs.
-
Example:
{ "error": "Unprocessable Entity", "message": "Validation failed for one or more fields.", "details": { "field": "username", "error": "Username already exists." } }
11. 429 Too Many Requests
- Description: The user has sent too many requests in a given amount of time ("rate limiting").
-
Example:
{ "error": "Too Many Requests", "message": "You have exceeded the rate limit. Please try again later." }
12. 500 Internal Server Error
- Description: The server encountered a situation it doesn't know how to handle. This is a generic error message for unexpected conditions.
-
Example:
{ "error": "Internal Server Error", "message": "An unexpected error occurred on the server." }
13. 502 Bad Gateway
- Description: The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
-
Example:
{ "error": "Bad Gateway", "message": "The server received an invalid response from the upstream server." }
14. 503 Service Unavailable
- Description: The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded.
-
Example:
{ "error": "Service Unavailable", "message": "The service is temporarily unavailable. Please try again later." }
15. 504 Gateway Timeout
- Description: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI.
-
Example:
{ "error": "Gateway Timeout", "message": "The server did not receive a timely response from the upstream server." }
16. 502 Invalid Token
- Description: The token provided in the request is invalid, expired, or missing.
-
Example:
{ "error": "Invalid Token", "message": "The token provided is either invalid or has expired. Please authenticate again." }
17. 404 Resource Not Found
- Description: The requested resource could not be found. This is similar to a generic 404 error but more specific to API resources.
-
Example:
{ "error": "Resource Not Found", "message": "The specified resource was not found." }
18. 400 Missing Parameters
- Description: Required parameters for the request are missing or incomplete.
-
Example:
{ "error": "Missing Parameters", "message": "Required parameters are missing from the request." }
19. 405 Rate Limit Exceeded
- Description: The client has exceeded the number of requests allowed in a given period.
-
Example:
{ "error": "Rate Limit Exceeded", "message": "You have made too many requests in a short period of time. Please slow down." }
20. 403 Insufficient Permissions
- Description: The client does not have the required permissions to access the resource.
-
Example:
{ "error": "Insufficient Permissions", "message": "You do not have the necessary permissions to access this resource." }