Vì vậy, tôi có một câu lệnh ghi nhật ký khá chung sau khi yêu cầu:
try:
r = requests.get[testUrl, timeout=10.0]
except Exception, err:
logger.error[{"message": err.message}]
Điều này hoạt động tuyệt vời cho tất cả mọi thứ tôi đã ném vào nó ngoại trừ
except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
5. Khi yêu cầu hết thời gian, tôi nhận được lại là một bộ dữ liệu mà nó cố gắng và không tuần tự hóa.Câu hỏi của tôi là làm thế nào để tôi bắt được một loại lỗi này? Đối với người mới bắt đầu
except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
5 không phải là thứ tôi có quyền truy cập. Tôi đã thử thêm except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
7 nhưng không có may mắn. Tôi cũng đã thử nhập except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
8 vì các tài liệu nói except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
5 là một lớp con, nhưng tôi không thể truy cập except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
5 sau khi nhập except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
8.Docs Timeouterror
Tôi có kế hoạch liệt kê các trường hợp ngoại lệ của mình theo thứ tự:
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
Hoặc chỉ kiểm tra loại:
except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
Python 2.7.3 & Django 1.5
Mã trong sổ ghi chép này giúp xử lý lỗi. Thông thường, một lỗi trong mã Notebook khiến việc thực thi mã dừng lại; Trong khi một vòng lặp vô hạn trong mã máy tính xách tay khiến máy tính xách tay chạy mà không kết thúc. Sổ ghi chép này cung cấp hai lớp để giúp giải quyết những mối quan tâm này.
Điều kiện tiên quyết
- Sổ ghi chép này cần một số hiểu biết về các khái niệm nâng cao trong Python, đáng chú ý là
- các lớp học
- Tuyên bố Python
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
2 - Truy tìm
- thời gian đo
- ngoại lệ
Tóm tắt¶
Để sử dụng mã được cung cấp trong chương này, hãy viết
và sau đó sử dụng các tính năng sau.
Lớp
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]3 cho phép bạn bắt và báo cáo các ngoại lệ, nhưng vẫn tiếp tục thực thi. Điều này rất hữu ích trong sổ ghi chép, vì chúng thường làm gián đoạn thực thi ngay khi một ngoại lệ được nâng lên. Việc sử dụng điển hình của nó được kết hợp với mệnh đề
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]2:
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
Lớp
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]5 cho phép bạn làm gián đoạn thực thi sau thời gian được chỉ định. Điều này rất hữu ích cho việc gián đoạn mã có thể chạy mãi mãi.
>>> with ExpectTimeout[5]: >>> long_running_test[] Start 0 seconds have passed 1 seconds have passed 2 seconds have passed 3 seconds have passed Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/1223755941.py", line 2, in long_running_test[] File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/3930412460.py", line 4, in long_running_test time.sleep[1] File "/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb", line 43, in timeout_handler raise TimeoutError[] TimeoutError [expected]
Ngoại lệ và dấu vết liên quan được in dưới dạng thông báo lỗi. Nếu bạn không muốn điều đó, hãy sử dụng các tùy chọn từ khóa sau:
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
6 [mặc định đúng] có thể được đặt thành>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
7 để tránh dấu vết được in>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
8 [mặc định sai] có thể được đặt thành>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
9 để tránh hoàn toàn bất kỳ đầu ra nào.
Lấy lỗi lor
Lớp
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]3 cho phép thể hiện rằng một số mã tạo ra một ngoại lệ. Một cách sử dụng điển hình trông như sau:
from ExpectError import ExpectError with ExpectError[]: function_that_is_supposed_to_fail[]
Nếu một ngoại lệ xảy ra, nó được in trên lỗi tiêu chuẩn; Tuy nhiên, thực thi tiếp tục.
from types import FrameType, TracebackType
class ExpectError: """Execute a code block expecting [and catching] an error.""" def __init__[self, exc_type: Optional[type] = None, print_traceback: bool = True, mute: bool = False]: """ Constructor. Expect an exception of type `exc_type` [`None`: any exception]. If `print_traceback` is set [default], print a traceback to stderr. If `mute` is set [default: False], do not print anything. """ self.print_traceback = print_traceback self.mute = mute self.expected_exc_type = exc_type def __enter__[self] -> Any: """Begin of `with` block""" return self def __exit__[self, exc_type: type, exc_value: BaseException, tb: TracebackType] -> Optional[bool]: """End of `with` block""" if exc_type is None: # No exception return if [self.expected_exc_type is not None and exc_type != self.expected_exc_type]: raise # Unexpected exception # An exception occurred if self.print_traceback: lines = ''.join[ traceback.format_exception[ exc_type, exc_value, tb]].strip[] else: lines = traceback.format_exception_only[ exc_type, exc_value][-1].strip[] if not self.mute: print[lines, "[expected]", file=sys.stderr] return True # Ignore it
def fail_test[] -> None: # Trigger an exception x = 1 / 0
with ExpectError[]: fail_test[]
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
0except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
1except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
2Chúng tôi có thể chỉ định loại ngoại lệ dự kiến. Bằng cách này, nếu điều gì đó khác xảy ra, chúng tôi sẽ được thông báo.
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
3except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
4except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
5except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
6Bắt hết thời gian
Lớp
>>> with ExpectTimeout[5]: >>> long_running_test[] Start 0 seconds have passed 1 seconds have passed 2 seconds have passed 3 seconds have passed Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/1223755941.py", line 2, in long_running_test[] File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/3930412460.py", line 4, in long_running_test time.sleep[1] File "/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb", line 43, in timeout_handler raise TimeoutError[] TimeoutError [expected]1 cho phép thể hiện rằng một số mã có thể chạy trong một thời gian dài hoặc vô hạn; Thực thi do đó bị gián đoạn sau
>>> with ExpectTimeout[5]: >>> long_running_test[] Start 0 seconds have passed 1 seconds have passed 2 seconds have passed 3 seconds have passed Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/1223755941.py", line 2, in long_running_test[] File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/3930412460.py", line 4, in long_running_test time.sleep[1] File "/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb", line 43, in timeout_handler raise TimeoutError[] TimeoutError [expected]2 giây. Một cách sử dụng điển hình trông như sau:
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
7Nếu một ngoại lệ xảy ra, nó được in theo lỗi tiêu chuẩn [như với
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]3]; Tuy nhiên, thực thi tiếp tục.
Nếu cần phải hủy thời gian chờ trong khối
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]2,
>>> with ExpectTimeout[5]: >>> long_running_test[] Start 0 seconds have passed 1 seconds have passed 2 seconds have passed 3 seconds have passed Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/1223755941.py", line 2, in long_running_test[] File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/3930412460.py", line 4, in long_running_test time.sleep[1] File "/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb", line 43, in timeout_handler raise TimeoutError[] TimeoutError [expected]5 sẽ thực hiện thủ thuật.
Việc triển khai sử dụng
>>> with ExpectTimeout[5]: >>> long_running_test[] Start 0 seconds have passed 1 seconds have passed 2 seconds have passed 3 seconds have passed Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/1223755941.py", line 2, in long_running_test[] File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/3930412460.py", line 4, in long_running_test time.sleep[1] File "/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb", line 43, in timeout_handler raise TimeoutError[] TimeoutError [expected]6, vì đây dường như là cách di động nhất để thực hiện thời gian chờ. Nó không hiệu quả lắm, mặc dù. Ngoài ra, nó chỉ hoạt động trên các dòng riêng lẻ của mã python và sẽ không làm gián đoạn chức năng hệ thống dài.
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
8except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
9except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
0except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
1Lưu ý rằng có thể làm tổ nhiều thời gian chờ.
except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
2except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
3except Exception, err:
if isinstance[err, TimeoutError]:
#handle specific error
#handle all other errors
1
Đó là nó, folks - & nbsp; Thưởng thức!
Bài học kinh nghiệm Bur
- Với lớp
>>> with ExpectError[]: >>> x = 1 / 0 Traceback [most recent call last]: File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_16935/2664980466.py", line 2, in x = 1 / 0 ZeroDivisionError: division by zero [expected]
3, rất dễ xử lý các lỗi mà không làm gián đoạn việc thực thi sổ ghi chép.