Bonjour,
Je suis actuellement sur la gestion des erreurs avec une WebAPI.
L'objectif était de pouvoir renvoyer au client un codes http custom (450,452,...) et de renvoyer un objet "WebAPIException" sérialisé en json
J'ai trouvé une solution mais je la trouve pas terrible. J'ai ajouté un ExceptionFilterAttribute qui agit de la façon suivante:
Derrière ça mon serialiser json (Json.Net) transforme le status code dans la réponseCode:
1
2
3
4
5 public override void OnException(HttpActionExecutedContext actionExecutedContext) { actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse<WebAPIException>(HttpStatusCode.OK, exception as WebAPIException); }
Ce code fonctionne renvoie un objet json sérialisé comme suitCode:
1
2
3
4
5
6
7
8
9
10
11
12
13 public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext) { // Create a serializer JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; if (type == typeof(WebAPIException)) { response.StatusCode = ((WebAPIException)value).HttpStatusCode; } return Task.Factory.StartNew(() => { this.Serialize(serializer, value, writeStream); }); }
Dans l'ensemble je trouve ce moyen très sale.Code:
1
2
3
4
5 { "message" : "error in the synchronisation" "errKey" : "syncerror12" }
Du coup je voulais avoir votre avis pour réaliser ça de manière plus propre.