Oui c'est ça il faut passer par un FaultContract. Il te permet de définir dans ton contrat les types d'erreurs renvoyés par le service.
C'est un tag à mettre au dessus des méthodes
[FaultContract(typeof(BusinessExceptionDetail))]
Ensuite dans ton service il te suffit de déclencher une FaultException<BusinessExceptionDetail> pour qu'elle soit transférée avec tous les détails côté client.
J'ai créé un aspect PostSharp qui fait ça, je te le donne pour l'exemple, ce n'est pas une nécessité car tu peux décider de faire cette gestion à la main.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| [Serializable]
public class ServiceExceptionHandler : OnExceptionAspect
{
/// <summary>
/// Called when a exception is raised in the target.
/// </summary>
/// <param name="eventArgs">Parameters for the OnException event</param>
/// <inheritdoc/>
public override void OnException(MethodExecutionEventArgs eventArgs)
{
// The exception is a BusinessException
if (eventArgs.Exception is BusinessException)
{
throw new FaultException<BusinessExceptionDetail>(
new BusinessExceptionDetail(eventArgs.Exception as BusinessException),
new FaultReason(eventArgs.Exception.Message));
}
// The exception is a TechnicalException
if (eventArgs.Exception is TechnicalException)
{
throw new FaultException<TechnicalExceptionDetail>(
new TechnicalExceptionDetail(eventArgs.Exception as TechnicalException),
new FaultReason(eventArgs.Exception.Message));
}
// In case of a FaultException, the exception is simply bubbled up (useful for handling exceptions from another service).
if (eventArgs.Exception is FaultException)
{
eventArgs.FlowBehavior = FlowBehavior.RethrowException;
}
else if (eventArgs.Exception is ArgumentValidationException)
{
var detail = new BusinessExceptionDetail((ArgumentValidationException) eventArgs.Exception);
throw new FaultException<BusinessExceptionDetail>(detail, detail.Message);
}
else
{
throw new FaultException<TechnicalExceptionDetail>(
new TechnicalExceptionDetail(new TechnicalException("System error", eventArgs.Exception)),
new FaultReason(eventArgs.Exception.Message));
}
}
} |
Partager