Puede adquirir el objeto de excepción antes de llamar a su controlador y mantener el manejador en sí mismo un liner. Sin embargo, todavía tiene una gran cantidad de carga "Try/Except/Do/End".
Procedure MyExceptionHandler(AException: Exception);
Begin
Log(AException); // assuming it accepts an exception
ShowMessage(AException.Message);
raise AException; // the ref count will be leveled if you always raise it
End;
Procedure TForm3.Button1Click(Sender: TObject);
Begin
Try
Foo;
Except On E:Exception Do
MyExceptionHandler(Exception(AcquireExceptionObject));
End;
End;
Sin embargo, si lo que sólo desea hacer es deshacerse de código de control de errores repetitivos en los controladores de eventos, podría intentar esto:
Procedure TForm3.ShowException(AProc : TProc);
Begin
Try
AProc;
Except On E:Exception Do Begin
Log(E);
ShowMessage(E.Message);
End; End;
End;
La reducción de su código de controlador de eventos a esto:
Procedure TForm3.Button1Click(Sender: TObject);
Begin
ShowException(Procedure Begin // anon method
Foo; // if this call raises an exception, it will be handled by ShowException's handler
End);
End;
también puede hacer que funcione para funciones, utilizando funciones parametrizadas:
Function TForm3.ShowException<T>(AFunc : TFunc<T>) : T;
Begin
Try
Result := AFunc;
Except On E:Exception Do Begin
Log(E);
ShowMessage(E.Message);
End; End;
End;
Y haciendo ShowException devolver un valor (que actúa como un tránsito):
Procedure TForm3.Button1Click(Sender: TObject);
Var
V : Integer;
Begin
V := ShowException<Integer>(Function : Integer Begin // anon method
Result := Foo; // if this call raises an exception, it will be handled by ShowException's handler
End);
End;
O incluso haciendo el procedimiento anon toque directamente la variable (s) ámbito exterior:
Procedure TForm3.Button1Click(Sender: TObject);
Var
V : Integer;
Begin
ShowException(Procedure Begin // anon method
V := Foo; // if this call raises an exception, it will be handled by ShowException's handler
End);
End;
hay algunas limitaciones en la interacción de variables desde el interior del cuerpo de la función anónima y las definidas en el ámbito externo, pero para casos simples como estos, estará más que bien.
Simplemente vuelva a subirlo de la forma habitual. Mantiene su código auto-documentado y no estropea el trazado de la pila. –
sí definitivamente quiero preservar la pila! –
Si está registrando las excepciones que está buscando, debería echar un vistazo a madExcept, EurekaLog y/o Jedi. Cada uno tiene un mejor manejo del registro de excepción que nunca soñaría con hacer usted mismo. –