You have not described why the answers above do not fit your case. Given that you use a Pascal, the event listeners may be used fully, including e.g. throwing
CloseVetoException from XCloseListener::queryClosing.
However, there may be another way to bind something to the document events - but note that that is a document change, so it would be saved with the document, and make the saved handle to attempt to execute on following document operations (with respective security warnings). For that, you assign handlers (macros) to the events by name, like this (Basic code):
Sub SetupOnPrepareUnload(oDoc, sMacro)
Dim descriptor(1) as new com.sun.star.beans.PropertyValue
descriptor(0).Name = "EventType"
descriptor(0).Value = "Script"
descriptor(1).Name = "Script"
descriptor(1).Value = "vnd.sun.star.script:" & sMacro & "?language=Basic&location=application"
oDoc.getEvents().replaceByName("OnPrepareUnload", descriptor())
End Sub
This has only one advantage IMO: the possibility to stop unloading documents from languages that do not allow throwing exceptions, like Basic.