from typing import Optional, Union
class BeCAError(Exception):
error_code = None
message = None
def __init__(self, error_code_or_message: Optional[Union[str, int]], message: Optional[str] = None):
"""
Constructor that can be invoked in one of three ways:
- With error_code and message passed explicitly.
- With only error_code (and message retrieved from self.error_messages)
- With only message (and error_code retrieved from self.error_code)
"""
# when invoked with one argument, it can be either error_code or message, so figure that out:
if isinstance(error_code_or_message, int):
error_code = error_code_or_message
elif error_code_or_message is not None:
assert message is None
message = error_code_or_message
error_code = None
if error_code is not None:
# if an error code was passed explicitly, use that
self.error_code = error_code
else:
# otherwise, ensure we have a default error code
assert self.error_code is not None
if message is not None:
# if an error message was passed explicitly, use that
self.message = message
elif self.message is None:
# otherwise, look up the message for this error_code
self.message = self.error_messages[self.error_code]
super().__init__(message)
def __str__(self):
return self.message
Assistant
User
Assistant
The BeCAError class is a custom exception class in Python, which is designed to provide flexible initialization based on the presence of either an error code, an error message, or both. Below are the key aspects and usage of this class:
Key Features of the BeCAError Class
Inheritance from Exception: The class inherits from Python's built-in Exception class, making it a standard exception that can be caught and handled like any other exception in Python.
Flexible Initialization:
The constructor (__init__) allows for three ways to create an instance of BeCAError:
With both error_code and message: You can explicitly provide both an error code and a message.
With only error_code: If only an integer (error code) is provided, the class can use a predefined error message associated with that code. However, you need to ensure that self.error_messages is defined (which should typically be a class-level dictionary mapping error codes to messages).
With only message: If only a message is provided, a default or predefined error code can also be specified.
Default Error Code and Message Lookup: If no error_code or message is provided, the class checks to ensure that it has a default error code and attempts to retrieve the corresponding message from a class-level attribute self.error_messages.
String Representation: The __str__ method returns the error message, allowing the exception to be easily readable when printed.
Example Usage
Here’s how you might use the BeCAError class in practice:
python
# Sample error messages dictionary
BeCAError.error_messages = {
404: "Not Found",
500: "Internal Server Error",
401: "Unauthorized",
}
try:
# Raising error with both code and message
raise BeCAError(404, "Resource not available")
except BeCAError as e:
print(f"Error Code: {e.error_code}, Message: {e}")
try:
# Raising error with only code
raise BeCAError(500)
except BeCAError as e:
print(f"Error Code: {e.error_code}, Message: {e}")
try:
# Raising error with only message
raise BeCAError("Custom error message")
except BeCAError as e:
print(f"Error Code: {e.error_code}, Message: {e}")
Summary
The BeCAError class is a versatile custom exception that can help in error handling within a Python application by allowing errors to be initialized with varying degrees of specificity. The ability to use both error codes and messages makes it useful for APIs or applications where standardized error reporting is required.
how to use show only neccessary data for the error using the custom exception
code
TypeError: expected string or bytes-like object
Traceback:
File "C:\Users\AL03207\AppData\Roaming\Python\Python39\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 88, in exec_func_with_error_handling
result = func()
File "C:\Users\AL03207\AppData\Roaming\Python\Python39\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 590, in code_to_exec
exec(code, module.__dict__)
File "C:\AJAY\ai-test-case-automation\src\app_st.py", line 181, in <module>
st.session_state.app.generate_results(step="verified_io_types")
File "C:\AJAY\ai-test-case-automation\src\data_handler.py", line 228, in generate_results
langgraph_state = langgraph_assistant(output=langgraph_values, as_node=node)
File "C:\AJAY\ai-test-case-automation\src\code_generator.py", line 461, in langgraph_assistant
for output in app.stream(None, thread, stream_mode="values"):
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\pregel\__init__.py", line 1221, in stream
for _ in runner.tick(
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\pregel\runner.py", line 87, in tick
_panic_or_proceed(all_futures)
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\pregel\runner.py", line 190, in _panic_or_proceed
raise exc
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\pregel\executor.py", line 59, in done
task.result()
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\concurrent\futures\_base.py", line 439, in result
return self.__get_result()
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\concurrent\futures\_base.py", line 391, in __get_result
raise self._exception
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\concurrent\futures\thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\pregel\retry.py", line 26, in run_with_retry
task.proc.invoke(task.input, task.config)
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\utils\runnable.py", line 341, in invoke
input = context.run(step.invoke, input, config, **kwargs)
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\site-packages\langgraph\utils\runnable.py", line 129, in invoke
ret = context.run(self.func, input, **kwargs)
File "C:\AJAY\ai-test-case-automation\src\code_generator.py", line 172, in clarifier
generated_dict, err = process_json(get_llm_response(system_prompt, input_prompt))
File "C:\AJAY\ai-test-case-automation\src\processing\result_processing.py", line 58, in process_json
json_match = re.search(r"\{.*\}", llm_output, re.DOTALL)
File "C:\AJAY\ai-test-case-automation\env\test_case_automation\lib\re.py", line 201, in search
return _compile(pattern, flags).search(string)
When dealing with custom exceptions, you might want to control the output error message to only include relevant and necessary information for clarity and professionalism. You can modify the way the exception is raised and how errors are handled in your code so that only the essential details are displayed.
Assuming you want to use the BeCAError class from your previous example to encapsulate error handling in your application, here’s how you can do it to showcase only necessary data when an error occurs.
Step-by-Step Implementation
Define the Error Messages: First, you need a mapping for your error codes to error messages. This can be done as a class attribute.
Use the Custom Exception: In your code, wrap the sections that could raise exceptions in try-except blocks and raise your custom exception accordingly.
Customize the Output: In the except block, you can determine how much information you want to display based on the exception type.
Example Code
Here's how you might modify the error handling in your application using your BeCAError class:
python
import re
from typing import Optional, Union
class BeCAError(Exception):
error_code: Optional[int] = None
message: Optional[str] = None
error_messages = {
404: "Not Found",
500: "Internal Server Error",
1001: "TypeError: Invalid input type provided.",
}
def __init__(self, error_code_or_message: Optional[Union[str, int]], message: Optional[str] = None):
if isinstance(error_code_or_message, int):
error_code = error_code_or_message
elif error_code_or_message is not None:
assert message is None
message = error_code_or_message
error_code = None
if error_code is not None:
self.error_code = error_code
else:
assert self.error_code is not None
if message is not None:
self.message = message
elif self.message is None:
self.message = self.error_messages.get(self.error_code, "An unknown error occurred.")
super().__init__(self.message)
def __str__(self):
return f"[Error {self.error_code}] {self.message}"
def process_data(user_input):
# Simulated processing function
if not isinstance(user_input, str):
raise BeCAError(1001) # Custom TypeError
# More processing here
return "Processed successfully."
# Example usage in the main application
try:
result = process_data(42) # This will raise an error
except BeCAError as e:
print(f"An error occurred: {e}")
# Example with a regex that might fail
def process_json(llm_output):
try:
json_match = re.search(r"\{.*\}", llm_output, re.DOTALL)
if json_match is None:
raise BeCAError(404)
return json_match.group(0)
except Exception as e:
raise BeCAError("An unexpected error occurred during JSON processing.")
# Using the function
try:
json_result = process_json("Invalid output") # Invalid would cause a 404
except BeCAError as e:
print(f"An error occurred: {e}")
Explanation
Error Codes and Messages: The error_messages dictionary contains translated error messages associated with specific error codes. You can add more error codes as needed.
Raising Custom Exceptions: In both process_data() and process_json() functions, you raise a BeCAError when you encounter a condition that warrants an exception.
Controlled Output: In the catch block, we can control the output by determining what to show based on the type of error that occurs. Here, the error messages are clean, meaningful, and concise, providing only necessary information.
When the program runs, if a BeCAError is raised, it will print an understandable error message instead of the full traceback, focusing on the error code and relevant message. You can further customize this behavior to add logging or more context based on requirements.