Skills Error Handling and Fault Tolerance
A Skill that can only run under ideal conditions is fragile.
A robust Skill needs to anticipate common errors, give clear feedback, and recover automatically whenever possible.
Three levels of error handling
| Level | When it occurs | Handling Method |
|---|---|---|
| Input validation errors | Before execution | Check the input, reject it directly if invalid, and explain the reason |
| Runtime errors | During script execution | Catch exceptions and output structured error messages |
| Result anomalies | After execution completes | Verify whether the output meets expectations; if not, trigger a remediation process |
Define error handling strategies in SKILL.md
SKILL.md should contain a clear error handling section telling Claude what to do when problems arise.
Example
Error handling
Input problems
-
File does not exist: tell the user the file path is wrong and ask them to upload again
-
Unsupported file format: list the supported formats (pdf, docx, txt) and ask the user to convert and retry
-
File is empty: tell the user the file content is empty and cannot be processed
Execution problems
-
Script execution failed: show the complete error message to the user, do not hide it
-
Dependencies not installed: first try to install automatically (pip
install
), if it fails, tell the user to install manually
- Timeout: if it exceeds
60
seconds without completing, output the current progress and ask the user whether to continue waiting
Result problems
-
Output file is empty: re-check the processing logic and explain possible causes to the user
-
Output format does not meet expectations: show the actual output and ask the user if they are satisfied
Standard error handling patterns in scripts
Python scripts should use try-except structures and uniformly return JSON containing a status field.
Example
File path: scripts/error_handling_demo.py
import
json
import
sys
import
os
class
SkillError
(
Exception
)
:
"""Custom Skill exception base class"""
def
init
(
self
,
message:
str
,
code
:
str
)
:
self
.
message
=
message
self
.
code
=
code
Error code, so the program can determine the error type
super
(
)
.
init
(
message
)
class
InputError
(
SkillError
)
:
"""Input validation error"""
pass
class
ProcessError
(
SkillError
)
:
"""Processing error"""
pass
def
validate_input
(
file_path:
str
)
None
:
"""Validate input, raise InputError on error"""
if
not
file_path:
raise
InputError
(
"No file path provided"
,
"MISSING_FILE"
)
if
not
os
.
path
.
exists
(
file_path
)
:
raise
InputError
(
f
"File does not exist: {file_path}"
,
"FILE_NOT_FOUND"
)
if
os
.
path
.
getsize
(
file_path
)
==
0
:
raise
InputError
(
f
"File content is empty: {file_path}"
,
"EMPTY_FILE"
)
def
process
(
file_path:
str
)
dict
:
"""Main processing logic"""
try
:
validate_input
(
file_path
)
with
open
(
file_path
,
"r"
,
encoding
=
"utf-8"
)
as
f:
content
=
f.
read
(
)
Actual processing logic (simplified here to line count)
lines
=
content.
split
(
"\n"
)
return
{
"status"
:
"success"
,
"data"
:
{
"file"
: file_path
,
"lines"
:
len
(
lines
)
,
"chars"
:
len
(
content
)
}
}
except
InputError
as
e:
Input error: the user can correct it and retry
return
{
"status"
:
"input_error"
,
"code"
: e.
code
,
"message"
: e.
message
,
"hint"
:
"Please check whether the file path is correct and the file exists and is non-empty"
}
except
UnicodeDecodeError
:
Encoding error: give specific repair suggestions
return
{
"status"
:
"process_error"
,
"code"
:
"ENCODING_ERROR"
,
"message"
:
"File encoding is not UTF-8 and cannot be read"
,
"hint"
:
"Please save the file as UTF-8 and retry"
}
except
Exception
as
e:
Unexpected errors: log them completely for easier debugging
return
{
"status"
:
"unexpected_error"
,
"code"
:
"UNKNOWN"
,
"message"
:
str
(
e
)
,
"hint"
:
"Please report the above error information to the developer"
}
if
name
==
"main"
:
file_path
=
sys
.
argv
[
1
]
if
len
(
sys
.
argv
)
1
else
""
result
=
process
(
file_path
)
(
json.
dumps
(
result
,
ensure_ascii
=
False
,
indent
=
2
)
)
# Successful output when the file exists:
{
"status": "success",
"data": {
"file": "/mnt/user-data/uploads/runoob.txt",
"lines": 128,
"chars": 5432
}
}
# Error output when file does not exist:
{
"status": "input_error",
"code": "FILE_NOT_FOUND",
"message": "文件不存在:/mnt/user-data/uploads/missing.txt",
"hint": "请检查文件路径是否正确,文件是否存在且非空"
}
Fault-tolerant pattern for automatic dependency installation
When a Python package that a script depends on is not installed, the script can automatically try to install it.
Example
File path: scripts/auto_install_demo.py
import
subprocess
import
sys
def
ensure_package
(
package_name:
str
,
import_name:
str
=
None
)
bool
:
"""
Ensure a Python package is installed; if not, install it automatically
Parameters:
package_name: the package name used for pip installation (e.g. "python-docx")
import_name: the name used when importing (e.g. "docx"), defaults to the same as package_name
"""
import_name
=
import_name
or
package_name
try
:
import
(
import_name
)
return
True
Installed
except
ImportError
:
(
f
"Installing dependency: {package_name}..."
)
result
=
subprocess
.
run
(
[
sys
.
executable
,
"-m"
,
"pip"
,
"install"
,
package_name
,
"--break-system-packages"
,
"--quiet"
]
,
capture_output
=
True
,
text
=
True
)
if
result.
returncode
==
0
:
(
f
"Installation successful: {package_name}"
)
return
True
else
:
(
f
"Installation failed: {package_name}"
)
(
result.
stderr
)
return
False
Usage example: ensure all dependencies are ready at the start of the script
if
not
ensure_package
(
"pandas"
)
:
sys
.
exit
(
1
)
if
not
ensure_package
(
"openpyxl"
)
:
sys
.
exit
(
1
)
After dependencies are ready, import normally
import
pandas
as
pd
(
"All dependencies are ready, starting execution..."
)
Automatic installation only applies to development and lightweight scenarios. In production Skills, dependencies should be documented and pre-installed by users rather than installed automatically at runtime.
Guidelines for writing error messages
Good error messages help users quickly locate problems, while bad ones only cause confusion.
| Dimension | Bad writing | A good way to write it |
|---|---|---|
| Describe the problem | "An error occurred" | "File report.csv does not exist in the upload directory" |
| Explain the cause | (none) | "The file name may be misspelled, or the file has not been uploaded yet" |
| Provide an action | (none) | "Please upload the file again, or check whether the file name is correct" |
Example
Bad error message
raise
Exception
(
"Error"
)
Good error message
raise
InputError
(
"File runoob_data.csv was not found in the upload directory."
"Possible causes: the file name is misspelled, or the file has not been uploaded yet."
"Please upload the file again and retry."
,
code
=
"FILE_NOT_FOUND"
)