Error handling
Contents

What is error handling?

Error handling in software development is the method of managing unexpected issues that come up during a program’s execution, such as invalid input, network problems, or missing files. It helps to ensure that the program doesn’t crash or behave unpredictably when something goes wrong.

Instead, error handling allows the software to respond properly, either by recovering, providing helpful feedback to the user, or avoiding data loss. The goal is to make the program more reliable and stable, even when things don’t go as planned.

Why error handling is crucial

Proper error handling is essential in developing high-quality software for several important reasons:

Ensuring the system is reliable and stable: Without proper error handling, an unexpected problem can cause a program to crash, freeze, or become unstable. This can disrupt functionality, make the system unusable, and potentially result in data loss.
Improving user experience: A program that crashes or shows confusing error messages makes the user experience worse. Proper error handling provides clear, understandable messages that explain what went wrong and how to fix it, helping users trust the software.
– Preventing data corruption and loss: Errors, especially those involving file handling or databases, can lead to data corruption or loss if not managed properly. Good error handling can include safeguards like rollback mechanisms or validations to protect important information.
Helping with debugging and maintenance: When an error happens, effective error handling can collect important details about the issue (e.g., error codes, stack traces). This helps developers quickly identify the cause of the problem, making debugging and future maintenance easier.
Improving security: Poor error handling can expose sensitive information about a system, creating security risks. Proper error handling helps prevent this type of information from leaking and reduces vulnerabilities.
Meeting business requirements: For many applications, especially in critical areas like finance, healthcare, or sports, continuous availability and accuracy are essential. Good error handling is necessary to meet service level agreements (SLAs) and ensure business continuity.

Common types of errors

Errors in software can appear in different ways, each needing a specific approach to fix. 

Syntactic errors (compile-time errors)

These are mistakes in the code’s structure that break the rules of the programming language. They are usually caught by the compiler or interpreter before the program runs. 

Examples: Typos in keywords, missing semicolons, or unclosed parentheses (brackets). While easy to fix, they prevent the program from compiling and are one of the most basic types of errors.

For instance, when using a sports data API like Sportmonks, a runtime error might occur if an API endpoint is temporarily unavailable (e.g., HTTP 503 Service Unavailable or 502 Bad gateway error). Sportmonks’ API returns a JSON response with an error message and code, allowing developers to handle such exceptions gracefully, such as by retrying the request after a delay.

 

Runtime errors (exceptions)

These errors happen when the program is running. The syntax may be correct, but something unexpected occurs that stops the program from running normally. These errors are often the focus of error handling mechanisms in the code.
Examples: Dividing by zero (arithmetic error), trying to open a non-existent file, accessing an offline database, running out of memory, or a network connection failing during a data transfer.

 

Logical errors

These are tricky because they don’t cause the program to crash or show a clear error message. The program runs, but it gives incorrect results. The code is syntactically correct, but the application logic behind it is flawed.

Examples: An incorrect formula, a loop running one too many or too few times, or a condition that evaluates wrongly, leading to the wrong section of code being executed. Finding these errors often needs careful tracing of the program’s flow and values.

Environmental/external errors

These errors come from outside the software itself, usually from the environment in which the program is running.

Examples: Hardware failures (like disk errors), issues with the operating system, network problems, external services being down (such as an unavailable API), or not having enough system resources (like disk space). While the software can’t fix these issues, good error handling lets it react properly, such as by retrying, logging the problem, or notifying the user.

Key principles of effective error handling

Effective error handling is about more than just writing try-catch blocks; it’s about having a strategy to foresee and manage potential issues. The key principles are:

Anticipation

This means thinking about what could go wrong when interacting with external systems (like databases, APIs, or file systems), handling user input, or performing complex calculations. Planning for errors from the beginning helps avoid problems later.

Graceful degradation: If a major error happens that prevents full recovery, the system should “degrade gracefully.” Instead of crashing, it should fail in a controlled way. For example, if a live data feed fails, the app might display cached data or show a message explaining that updates are temporarily unavailable, instead of freezing.
Informative messaging: Error messages should be clear, brief, and helpful. For users, they should explain what went wrong and, if possible, suggest how to fix it. For developers or administrators, messages should include enough technical information (like error codes or stack traces) to help solve the problem quickly.
Logging: Every major error should be logged. Logs help with debugging, monitoring system health, and spotting recurring issues. Good logs should include details like the type of error, the time it happened, where it occurred, and any relevant input values.
– Recovery/correction: Error handling should try to recover automatically, or guide the system to a stable state. This might mean retrying an action after a short delay, using an alternative resource, or asking the user to correct their input. The aim is to reduce disruption and keep the program working.
– Fail fast (when appropriate): For critical errors (like configuration issues or unrecoverable states), it might be better for the program to “fail fast”, stopping immediately with a clear error message. This prevents the system from continuing in a broken state and causing more damage or incorrect data.
Consistency: Error handling should be consistent throughout the entire application. Using the same methods for logging, error messages, and handling exceptions makes the system easier to understand, maintain, and fix.

Common strategies and mechanisms for error handling

Developers use various strategies and language-specific mechanisms for effective error handling. The approach often depends on the error type, programming language, and the application context:

Try-catch blocks (exception handling)

A common and powerful mechanism in many modern programming languages (e.g., Python, Java, C#, JavaScript). Code that might cause an error (an “exception”) is placed in a try block. If an exception happens, the normal program flow is interrupted, and control moves to a catch clause/block (or except in Python). The catch block handles the exception. This allows normal code flow to remain separate from error-handling logic.

Example: Trying to open a file. If the file doesn’t exist, a FileNotFoundError is caught, and the program can inform the user or create the file.

 

Error codes and return values

In languages where exceptions aren’t used (e.g., C or older APIs), functions often return specific error codes or values (e.g., null, -1, or false) to indicate success or failure. The calling code then checks these values and takes action.

Example: A function connecting to a database might return 0 for success, or 101 for a connection error, and 102 for an authentication failure.

 

Input and data validation

A proactive strategy where inputs (e.g., from users, files, or APIs) are validated before processing. This prevents many runtime errors by catching invalid data early. Validation can check data types, ranges, formats, and completeness.

Example: Ensuring a user-entered age is positive or that a football player’s name is not empty.

Logging and monitoring systems

More advanced than basic print statements, logging frameworks (e.g., Log4j, Winston) record error details, warnings, and messages to storage. These logs are then analysed by monitoring systems that alert administrators to critical issues, track error trends, and offer insights for proactive maintenance.

 

Circuit breakers and retries (for external services)

When dealing with external services (like APIs or databases), patterns like “Circuit breakers” are used. If failures reach a certain point, the breaker “trips” and prevents further calls, giving the service time to recover. “Retries” attempt a failed operation again, often with increasing delays, assuming the failure is temporary (e.g., a brief network issue).

Assertions

Assertions are checks in the code to ensure certain conditions are true during execution. If an assertion fails, it indicates a problem in the program’s logic. Assertions are mostly used during development and testing and are often disabled in production.

Impact of poor error handling

The lack of error handling can lead to serious problems for software applications, users, and organisations:

Frequent crashes and instability: Without proper error management, a program may crash or freeze often, making it unreliable and frustrating for users. This can lead to downtime and a poor reputation for quality.
Poor user experience: Users may encounter unclear or confusing error messages, or no message at all, leaving them unsure about what went wrong or how to fix it.
Data corruption and loss: Unhandled errors, especially during important tasks like saving files or updating databases, can result in incomplete operations, corrupted data, or the permanent loss of valuable information. This can cause significant financial and operational problems.
Security vulnerabilities: Inadequate error handling can unintentionally reveal sensitive details about the system, such as database structures or file paths, through detailed error messages. This information can be exploited by attackers to launch further attacks.
Difficult and costly debugging: Without proper logging or clear error messages, developers have a hard time identifying the cause of an error. This makes debugging more difficult, increases maintenance costs, and delays fixes.
Loss of revenue and reputation: Frequent crashes or poor user experience due to unhandled errors can lead to lost sales, a damaged brand, and a competitive disadvantage.
Reduced productivity: Both users dealing with application bugs and developers constantly fixing issues experience decreased productivity due to poor error handling.
Unpredictable behaviour: Without a clear error-handling process, the system may enter an undefined state, leading to unpredictable or inconsistent behaviour that is hard to fix or reproduce.

Sportmonks’ approach to error handling

Sportmonks, a sports data API provider, implements error handling through standard HTTP status codes and custom error codes in API responses. This approach helps developers manage issues like unauthorised access or rate limits effectively.

Common error codes and meanings

The API uses both HTTP status codes and custom codes for specific errors. Below is a list of common codes and their meanings:

Code: 200; Meaning: Request succeeded.
Code: 400; Meaning: Bad Request: Request is malformed; check parameters and filters.
Code: 401; Meaning: Unauthorized: Request lacks authentication; verify API token.
Code: 403; Meaning: Forbidden: Access to resource not allowed with current plan.
Code: 429; Meaning: Too many requests: Hourly limit exceeded; wait for reset or upgrade plan.
Code: 500; Meaning: Internal Server Error: Internal issue; contact support if persistent.
Code: 5003; Meaning: Custom Pagination Limit: Requested page doesn’t exist; adjust &page= parameter.
Code: 5005; Meaning: Custom Rate Limit: Plan’s rate limit reached; wait for reset or upgrade.
Code: 5007; Meaning: Custom Insufficient Resources: Resource not in current subscription; update plan.
Code: 5002; Meaning: Custom Insufficient Includes: Include not accessible; update subscription or contact support.

JavaScript example for error handling

Here’s how developers can handle errors in JavaScript using the fetch API, checking status codes and parsing error responses:

 

const apiToken = 'YOUR_API_TOKEN';
const url = https://api.sportmonks.com/v3/football

fetch(url)
  .then(response => {
    if (!response.ok) {
      return response.json().then(errorData => {
        throw new Error(`Error ${response.status}: ${errorData.error} (Code: ${errorData.code})`);
      });
    }
    return response.json();
  })
  .then(data => {
    console.log('Data received:', data);
  })
  .catch(error => {
    console.error('API Error:', error);
  });

This code checks if the response is OK (200-299); if not, it parses the JSON error response and throws an error with details, enabling specific error handling. For more details, check out our  API documentation.

Explore Sportmonks’ football API today

Try out Sportmonks’ feature-rich API today. It provides data for over 2500+ leagues. You can be confident that your applications are well-protected with strong error handling and recovery systems that use codes to prevent crashes and application failures. Sign up for free at Sportmonks football API and start exploring.

Faqs about error handling

What is error handling?
Error handling in software development is the method of managing unexpected issues that come up during a program’s execution, such as invalid input, network problems, or missing files. It helps to ensure that the program doesn't crash or behave unpredictably when something goes wrong.
Why is error handling so important?
Error handling is crucial for several important reasons: it ensures the system is reliable and stable, improves user experience by providing clear feedback, prevents data corruption and loss, helps with debugging and maintenance, improves security by preventing sensitive information from leaking, and is necessary to meet business requirements for continuous availability and accuracy.
What are the goals of error handling?
The goals of error handling are to make the program more reliable and stable, allow it to respond properly (recover, provide feedback, or avoid data loss), ensure graceful degradation instead of crashing, provide clear and informative messages (for both users and developers), enable effective logging for debugging and monitoring, and facilitate recovery or correction of issues to minimize disruption.
What is API error handling?
API error handling is the process of managing errors that occur when a software application interacts with an external API (Application Programming Interface). It involves the API returning specific information, often through standard HTTP status codes and custom error codes in its responses, to help the calling application understand what went wrong (e.g., unauthorized access, bad request, rate limit exceeded) and respond appropriately.

Written by David Jaja

David Jaja is a technical content manager at Sportmonks, where he makes complex football data easier to understand for developers and businesses. With a background in frontend development and technical writing, he helps bridge the gap between technology and sports data. Through clear, insightful content, he ensures Sportmonks' APIs are accessible and easy to use, empowering developers to build standout football applications