Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with program errors

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to deal with program errors". Interested friends might as well take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to deal with program errors.

one

Program error type

1.1

Grammatical error

Syntax errors are caused by incorrect code in the source program, that is, the syntax (or lexical) rules are not followed when the program is written, and the wrong syntax code is written, resulting in the compiler being unable to interpret the source code correctly. it is usually caused by a typing error, which is detected in lexical analysis or parsing. Errors such as "illegal characters", "parentheses mismatch", "missing;" and so on.

1.2

Semantic error

A semantic error refers to an error in the source program that does not conform to the semantic rules, that is, an error caused by a statement trying to perform an impossible operation. Some semantic errors are detected at the time of semantic analysis, and some can only be detected at run time. Such as variable declaration error, scope error, datastore overflow and so on.

1.3

Logic error

A logic error refers to an error that occurs when the running result of a program is different from what the programmer imagines. Such errors do not directly lead to errors during compilation and running of the program, but the program does not execute as expected, resulting in incorrect running results, which is difficult to find. This kind of error can only be found by analyzing the results and comparing the results with the design.

two

HTTPException

We use the HTTPException module to return Response with an error message. HTTPException is a normal Python exception with additional data related to API access.

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]}

three

Add custom header information

Sometimes for HTTP errors, in some scenarios, we need to add custom header information

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]}

four

Custom exception handler

With the same exception utilities from Starlette in fastapi, we can add custom exception handlers. Suppose we have a custom exception UnicornException that we want to handle globally. With the help of @ app.exception_handler (), we can achieve our goal.

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}

five

Override the default exception handler

Fastapi has some default exception handlers. These handlers are responsible for returning the default JSON result when we throw a HTTPException exception or when there is illegal data in the request. We can rewrite these exception handlers.

5.1

Rewrite request check exception handler

When a request contains illegal data, a RequestValidationError exception is thrown inside the fastapi, and there is a default exception handler to handle it. We can rewrite the exception handler with @ 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

Override HTTPException exception handlers

In the same way, we can rewrite the HTTPException exception handler. For example, you might want to return error messages in plain text format instead of JSON format.

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

Reuse default exception handlers

We can import and reuse default exception handlers. We import the default exception handler from fastapi.exception_handlers.

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 errorships: {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 collection: {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}

In the example, we added a log output before throwing an exception. We can flexibly reuse the default exception handler according to our business needs.

six

Fastapi HTTPException vs. Starlette HTTPException

HTTPException in fastapi inherits from HTTPException of Starlette.

The only difference is that HTTPException in fastapi allows you to add header information to response. It is mainly used internally for OAuth 2.0 and some security-related functions.

Therefore, we usually throw a HTTPException exception for fastapi in our code. However, when we register the exception handler, we should register as the HTTPException of Starlette. In this way, when the internal code of Starlette or the Starlette extension throws Starlette HTTPException, our processor can catch and handle this exception normally. If we want to use both classes in our code, to avoid naming conflicts, we can rename one of the classes.

At this point, I believe you have a deeper understanding of "how to deal with program errors". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report