Is it a good pattern to raise exceptions in a python decorator? Is it a good pattern to raise exceptions in a python decorator? flask flask

Is it a good pattern to raise exceptions in a python decorator?


I ended up using decorators and throwing specific exceptions within them. For example:

The @validate_pid decorator raises InvalidPidException() which are caught in the except block of any consumer that calls the decorated method.

Advantages so far:

  • Controllers are much cleaner and there is a lot less code replication.
  • Fairly versatile solution, as I use these "business logic validation" decorators all over my code.

Disadvantages so far:

  • The decorator relies on certain keyname parameters to be passed when the decorated method is called, but some of these parameters are not used within the method itself. This can lead to some odd "dangling" parameters in the method signature.
  • I have some minor performance concerns. For example: the project validation decorator initializes a session and loads an object (Project) only to be loaded again in the decorated method itself. Just seems a little janky.


Option 1: It seems logical to create a specific Exception for your decorator because this will help the user know which exception is raised, if any, and why. The type of exception should, of course, appear in the decorator docstring for the caller to be able to know what to expect. This way you're not making the assumption the user knows what exception is raised but that he has read the doc - which is more likely assumption. However if the method is called often the caller will have to handle it every time. That's part of the deal when using a library, an API or someone else's code.

Option 2: It does not belong to the user to determine which exception is going to be raised. The user should be aware of it via the documentation, for example. It is messy and counter intuitive in term of API design.

Thinking about your question it made me think about the way Java works, especially if you use an IDE, when calling a method you will be warned - by the IDE and via the typing mechanism - that you should try/catch a given type of exception.

But in your case wouldn't be possible to raise a proper HTTPException with a specific message ?