How to set a hangup handler on the channel to a trunk (not the local/extension channel)

I never quite figured my questions from this post out, and I finally looped around to it today. Unfortunately, I still didn’t have success.

The simple version of what I’m trying to accomplish is that I want to hangup a call when I get a 603 response back from my proxy. Right now, the outbound route fails over to the next trunk in the list. The way I attempted to do that today was to set up a hangup handler on the outbound call and check the value in the ‘reason’ sip header (I don’t think I’ll be able to use the hangup cause since I think it’s already rewritten to 21 at this point. I’m planning on doing some pattern matching based on the contents of the reason sip header) to determine if I should end the call or continue on to the next trunk.

I’ve tried doing this via macro-dialout-trunk-predial-hook like so:
exten => s,n,Set(CHANNEL(hangup_handler_push)=custom-hangup-handler,s,1)
However, this hangup handler only gets called when the entire call terminates (once it has already failed through to the second trunk, dialed out successfully, and then terminated) rather than when the first trunk terminates the call.

I believe the problem is that the hangup handler is being set on the local channel (PJSIP/extension) rather than the channel from the PBX to the proxy/trunk.

It seems like it should be possible to interact with the ‘trunk channel’ here since it’s supposedly possible to set the sip headers sent to the trunk in the predial hook.Although that uses a freepbx subroutine and which maybe effectively handles touching the channel a different way (via the SET command, I believe)

I also see that the ‘crm-hangup’ and ‘app-missedcall-hangup’ handlers are being applied to the correct channel via the ‘func-apply-sipheaders’ context. I see that ‘func-apply-sip-headers’ has the line ‘include => func-apply-sipheaders-custom’, and despite reading that I shouldn’t use these includes, I also attempted to create a custom context with that name, but wasn’t able to get them linked either. I’d like to do this the ‘freepbx way’ without overriding generated dialplan, but I’m not sure what else to try.

I did attempt to add a hook via a trunk dial option Ttb(add-custom-hangup-handler^s^1), but I could never even get this context to be entered. Not sure if that’s deprecated or something else, but I also read it wasn’t a good idea to do it this way regardless.

Any thoughts or suggestions would be appreciated. How would you go about doing this?

FWIW, I’m running asterisk 21.3.1 and FreePBX 17.