[Twisted-Python] How to use defer.fail better...

glyph at divmod.com glyph at divmod.com
Mon Mar 30 15:02:32 EDT 2009

On 09:42 am, jan.bakuwel at omiha.com wrote:
>Hoi all,
>I'm writing a twisted/python SMTP server that accepts emails from a MTA
>using twisted. All works well, except that when I return a
>defer.fail(None) from processEmail to messageHandler.eomReceived (see
>below), twisted dumps the trace back of the last exception on stdout. 
>there a way to avoid this? I would like to handle the exception
>gracefully (with an exception handler) and would not like to see any
>trace back from it in my logs. I've read that using None as the
>parameter to defer.fail does exactly that... what should I use instead?

By the time you return, you need to have handled any exceptions.

If you want to separate exception handling into a separate function, use 
addErrback on the Deferred you have created.
>The other thing I would like to do better is to have a way to return
>smtp code 421 (service temporarily unavailable) rather than 550 (fatal)
>in those cases where I would like to indicate a (temporary) failure to
>receive the email. I've patched smtp.py (replace 550 -> 421) for this
>but would gladly hear about a way to do this without patching a 
>component on my system.

This is what twisted.python.failure.Failure.trap is for; you can catch 
specific exception types in your errbacks.

Please feel free to ask more specifically if this doesn't answer your 
question :).

More information about the Twisted-Python mailing list