Menu

Post image 1
Post image 2
1 / 2
0

Practical Tip– Centralize API Error Handling with a Wrapper

DEV Community·Chris Lee·about 1 month ago
#7X32kLdB
Reading 0:00
15s threshold

When working with multiple external services, each API can raise different exceptions, return inconsistent error formats, or require specific retry logic. By wrapping all calls in a single helper function you eliminate duplication, make debugging easier, and enforce a uniform response shape across your codebase. This also simplifies swapping out one service for another, since the rest of your application interacts only with the wrapper’s consistent interface. import requests import time import logging def call_api ( url , params = None , max_retries = 3 , backoff = 2 ): """ Sends a GET request and handles common errors. Returns a dict: { ' success ' : bool, ' data ' : <payload|None>, ' error ' : <str|None>} """ for attempt in range ( 1 , max_retries + 1 ): try : response = requests . get ( url , params = params , timeout = 10 ) response . raise_for_status () # HTTP errors (4xx/5xx) return { ' success ' : True , ' data ' : response . json (), ' error ' : None } except ( requests .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More