Custom Exceptions or not?

I wrote a fairly simple API library and the only errors that can possibly be raised are anything raised by or ValidationError by pydantic. Should I catch these errors and then throw a custom one or should I just re-export the exceptions from httpx and pydantic instead allowing people to do from mylib import ValidationError?

Can you add information this way?

For example, what errors do you expect to be raised from, exactly? What would the message look like if one of those were uncaught? What would you like them to say instead - can you be more helpful? Similarly for Pydantic errors - why would they get raised? Is it because, for example, the returned data from the POST request doesn’t fit into some user-provided model? If that’s what happens, perhaps it would be more useful for you to say that - because Pydantic doesn’t know where the validation-failing data came from.

I wouldn’t bother with custom exceptions for this. Don’t even reexport
them, just document that your API may raise these exceptions.

If you’re intending to conceal httpx or pydantic (eg to use
different backends than those sometime) then you might meaningfully
catch as raise something custom, but does this help the user of your
library? It’s hard to debug something low level happening in the backend
(here I mean eg httpx) is the exception’s been concealed.

If you’re catching and raising something custom, at least use the form:

 except ValidationError as e:
     raise MyCustomException(.....) from e

so that the causing exception is attached - that way the user can get
your high level, maybe context aware, exception and still have access to
the original cause for inspection.

1 Like

The ValidationError will only be raised on User input which already has a helpful enough message that I can’t meaningfully improve on it. might raise a 404 (requested data is missing) or 500 because the API isn’t exactly the most stable thing on the planet.