Reputation: 77
I have an ASP.NET 4.0 WCF service that I am calling using jQuery. I have the service configured to accept a JSON object as a string. Example:
{"name": Joe, "age": 32 }
Everything is working correctly if the JSON string is valid. If the JSON string is not valid I get a 500 Internal Server Error response. What I would like to know is how do I catch the error on the server side so I can handle it myself? I set a breakpoint on the method I am calling and it never gets hit. I am assuming the error is happening when the service is deserializing the string and therefore the object never gets passed as a parameter into my method.
I have looked at the FaultContract
attribute and it appears I can return some custom details about the exception but it still doesn't allow me to catch errors at the point it is deserializing the JSON string.
Interface
<ServiceContract()>
Public Interface IApplicationService
<OperationContract()>
<WebInvoke(method:="POST", _
BodyStyle:=WebMessageBodyStyle.WrappedRequest, _
ResponseFormat:=WebMessageFormat.Json,
RequestFormat:=WebMessageFormat.Json)> _
Function DeleteAlbum(albumId As Long) As DeleteAlbumResponse
End Interface
Javascript
var data = JSON.stringify({"albumId" : 53});
$.ajax({
url: '/api/application.svc/Web/DeleteAlbum',
data: data,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
})
.done(function (data) {
console.log(data);
})
.fail(function (jqxhr, textStatus, error) {
console.log(error);
});
Upvotes: 1
Views: 592
Reputation: 8795
From your comment, you would like to return a 200
even if the input JSON is invalid.
You would probably be better off handling this by having your WCF method accept any arbitrary data. Once in the method, validate it yourself by serializing/deserializing and then proceeding with your regular logic.
However, to add: By specifying a request format of XML or JSON, it is necessary that the client get it right - this is a best practice and is a good idea to leave the validation to the framework itself. By catering to arbitrary strings, you are creating an 'ambiguous' endpoint which may or may not work depending on the validation logic that you change.
Upvotes: 1