溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么處理程序錯誤

發(fā)布時間:2021-10-15 14:09:35 來源:億速云 閱讀:152 作者:iii 欄目:編程語言

本篇內(nèi)容主要講解“怎么處理程序錯誤”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“怎么處理程序錯誤”吧!

1

程序錯誤類型

1.1

語法錯誤

語法錯誤是因為源程序中不正確的代碼產(chǎn)生的,即在編寫程序時沒有遵守語法(或詞法)規(guī)則,書寫了錯誤的語法代碼,從而導(dǎo)致編譯器無法正確解釋源代碼而產(chǎn)生的錯誤,通常是由于錄入的錯誤引起的,它在詞法分析或語法分析時檢測出來。如“非法字符”、“括號不匹配”、“缺少;”之類的錯誤。

1.2

語義錯誤

語義錯誤是指源程序中不符合語義規(guī)則的錯誤,即一條語句試圖執(zhí)行一條不可能執(zhí)行的操作而產(chǎn)生的錯誤。語義錯誤有的在語義分析時檢測處來,有的在運行時才能檢測出來。如變量聲明錯誤、作用域錯誤、數(shù)據(jù)存儲區(qū)的溢出等錯誤。

1.3

邏輯錯誤

邏輯錯誤是指程序的運行結(jié)果和程序員的設(shè)想有出入時產(chǎn)生的錯誤。這類錯誤并不直接導(dǎo)致程序在編譯期間和運行期間出現(xiàn)錯誤,但是程序未按預(yù)期方式執(zhí)行,產(chǎn)生了不正確的運行結(jié)果,較難發(fā)現(xiàn)。這種錯誤只能通過分析結(jié)果,將結(jié)果與設(shè)計方案進行對比來發(fā)現(xiàn)。

2

HTTPException

我們用 HTTPException 模塊返回帶錯誤信息的 Response。HTTPException 是一個普通的 Python 異常,同時帶有與 API 訪問有關(guān)的附加數(shù)據(jù)。

from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"book": "Learn Python"}

@app.get("/items/{item_id}")async def read_item(item_id: str):    if item_id not in items:
       raise HTTPException(status_code=404, detail="Item not found")
   return {"item": items[item_id]}

3

添加自定義頭信息

有時候針對 HTTP 錯誤,在一些場景下,我們需要添加自定義頭信息

from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"book": "Learn Python"}

@app.get("/items-header/{item_id}")async def read_item_header(item_id: str):    if item_id not in items:        raise HTTPException(            status_code=404,            detail="Item not found",            headers={"X-Error": "error info"},
       )    return {"item": items[item_id]}

4

自定義異常處理器

在 fastapi 中借助 the same exception utilities from Starlette,我們可以添加自定義異常處理器。假設(shè)我們有個自定義異常 UnicornException,我們想在全局范圍內(nèi)處理這個異常。借助 @app.exception_handler(),就可以實現(xiàn)我們的目標。


from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse
class UnicornException(Exception):    def __init__(self, name: str):        self.name = name
app = FastAPI()
@app.exception_handler(UnicornException)async def unicorn_exception_handler(request: Request, exc: UnicornException):
   return JSONResponse(        status_code=418,        content={"message": f"Oops! {exc.name} did something. error"},    )
@app.get("/get_name_info/{name}")async def read_unicorn(name: str):    if name == "haishiniu":        raise UnicornException(name=name)
   return {"name": name}

5

重寫缺省異常處理器

fastapi 有一些缺省的異常處理器。當我們拋出 HTTPException 異?;蛘弋斦埱笥蟹欠〝?shù)據(jù)的時候,這些處理器負責(zé)返回默認的 JSON 結(jié)果。我們可以重寫這些異常處理器。

5.1

重寫請求校驗異常處理器

當一個請求包含非法數(shù)據(jù)的時候,fastapi 內(nèi)部會拋出 RequestValidationError 異常,并且有默認的異常處理器來處理。我們可以用 @app.exception_handler(RequestValidationError) 來重寫這個異常處理器。


from fastapi import FastAPI, HTTPExceptionfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import PlainTextResponsefrom starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
@app.exception_handler(StarletteHTTPException)async def http_exception_handler(request, exc):    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):    return PlainTextResponse(str(exc), status_code=400)

@app.get("/items/{item_id}")async def read_item(item_id: int):    if item_id == 3:        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")    return {"item_id": item_id}

5.2

重寫 HTTPException 異常處理器

同樣的方法,我們可以重寫 HTTPException 異常處理器。例如,你可能想返回純文本格式而不是 JSON 格式的錯誤信息。

from fastapi import FastAPI, HTTPExceptionfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import PlainTextResponsefrom starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
   return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.exception_handler(RequestValidationError)async def validation_exception_handler(request, exc):    return PlainTextResponse(str(exc), status_code=400)

@app.get("/items/{item_id}")async def read_item(item_id: int):    if item_id == 3:
       raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
   return {"item_id": item_id}

5.3

重用缺省異常處理器

我們可以導(dǎo)入并且重用缺省的異常處理器。我們從 fastapi.exception_handlers 導(dǎo)入缺省異常處理器。

from fastapi import FastAPI, HTTPExceptionfrom fastapi.exception_handlers import (    http_exception_handler,    request_validation_exception_handler,)
from fastapi.exceptions import RequestValidationErrorfrom starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
@app.exception_handler(StarletteHTTPException)async def custom_http_exception_handler(request, exc):    print(f"OMG! An HTTP error!: {repr(exc)}")    return await http_exception_handler(request, exc)

@app.exception_handler(RequestValidationError)async def validation_exception_handler(request, exc):    print(f"OMG! The client sent invalid data!: {exc}")    return await request_validation_exception_handler(request, exc)


@app.get("/items/{item_id}")async def read_item(item_id: int):    if item_id == 3:        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")    return {"item_id": item_id}

在示例中,我們在拋出異常之前添加了一條日志輸出。我們可以根據(jù)業(yè)務(wù)需求靈活的重用缺省異常處理器。

6

fastapi HTTPException 對比 Starlette HTTPException

fastapi 中 HTTPException 繼承自 Starlette 的 HTTPException。
唯一的區(qū)別 fastapi 中 HTTPException 允許你在 response 添加頭信息。主要在內(nèi)部用于 OAuth 2.0 以及一些安全相關(guān)的功能。
因此,通常我們在代碼中拋出 fastapi 的 HTTPException 異常。但是,當我們注冊異常處理器的時候,我們應(yīng)該注冊為 Starlette 的 HTTPException。這樣,當 Starlette 的內(nèi)部代碼或者 Starlette 擴展插件拋出 Starlette HTTPException 時,我們的處理器才能正常捕獲和處理這個異常。如果我們要在代碼中同時使用這兩個類,為了避免命名沖突,我們可以重命名其中一個類。

到此,相信大家對“怎么處理程序錯誤”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI