跳到正文
DEV Community· Puneet Khandelwal·· 35 分鐘前AI 評分50

為何你的 AI 編碼助手總是寫出糟糕的錯誤處理

Why Your AI Coding Assistant Is Writing Terrible Error Handling

AI 導讀

AI 編碼助手容易生成只涵蓋順利情況的程式碼,遇上網絡中斷、逾時或格式錯誤的回應時,可能無法妥善處理失敗。提示詞應明確要求處理逾時、速率限制及格式錯誤的資料,並禁止使用會隱藏錯誤的通用例外捕捉。嚴格的自動化 lint 工具和類型檢查器有助把關生成程式碼。

正文

Puneet Khandelwal

Most LLM code fails the second it hits production. Ask a model for an API client or a migration script, and you get pristine code for a world where nothing breaks. Network drops? Pools exhaust? The model wraps everything in a generic catch block that swallows the stack trace and logs a cheerful message.

This isn't a bug. It's training bias. Public code repos lean heavily toward happy paths and toy tutorials. When an LLM predicts the next token, it's incentivized to write clean-looking code instead of resilient code.

Stop treating AI like a junior dev who needs better prompts. Treat it like a literal macro processor. If you don't constrain failure modes explicitly, you ship silent bugs.

Take a standard prompt asking for a remote data fetch. You get this in Python:

import requests

def get_user_profile(user_id):
 response = requests.get(f"https://api.example.com/users/{user_id}")
 return response.json()

This assumes the network never drops, 504 timeouts don't exist, and responses are always valid JSON. If the server drops mid-stream, requests.get throws. If it returns an HTML error page, response.json crashes with a decode error. Your app hangs.

Production output requires shifting prompt engineering from what the code should do to what it's forbidden from ignoring. Enforce defensive boundaries upfront. Tell the model to handle timeouts, rate limits, and malformed payloads explicitly. That changes the token probability distribution.

Try this prompt structure instead: Write a Python function to fetch a user profile. You must explicitly catch connection timeouts, handle HTTP status codes other than 200, and validate that the response payload matches the expected schema before returning. Do not use generic exception catching. Every failure mode must be surfaced or wrapped in a domain-specific error.

The output changes completely. You get explicit error propagation, timeout params, and defensive type checks. The code is longer and uglier. That verbosity is the price of admission for real software.

As generation speeds up, code review bottlenecks shift. We aren't bottlenecked by typing speed anymore. We're bottlenecked by catching silent failure modes in generated code before it hits pipelines. Teams building strict automated linters and type checkers to police AI output pull ahead. Teams relying on human eyes to spot missing try-catch blocks spend maintenance windows debugging ghostly outages.

來源:DEV Community · dev.to