Passing exception data between two applications - c#

I don't know if this has been already answered or not. But, I am unable to find the example or cause of this problem.
Application 1:
try
{
//Read request and check for the request header element from the soap request
//validating request and salt
...here it might gets failed.
_requestValidationService.ValidateRequest();
}
catch (Exception ex)
{
ex.Data.Add("Exception", "test");
throw ex;
}
Application 2:
catch (Exception ex)
{
string aa = Convert.ToString(ex.Data["Exception"]);
throw ex;
}
I don't know what I am missing here. But aa seems to be always empty and ex.Data.Count is always zero.
I just want to pass one code between two applications without adding new class of an exception.
Note: These two applications are wcf calls.
[EDIT1]
Application 1 validate request is the IDispatchMessageInspector AfterReceiveRequest

Exceptions are not propagated to clients from a WCF service. Instead, a SOAP Fault (assuming you are using SOAP) will be sent to the client.
You can include exception details in the SOAP Fault, but in general it is not recommended to do so in production.
IMHO a better approach is to implement an IErrorHandler that provides the Fault with whatever data you want to send to the client, and also gives you the opportunity to log the exception server-side.
You can then catch FaultException on the client and have access to the data added by your custom error handler.

The exception class is designed by one throw / catch pair. If you should add any additional information to a cached exception, use the inner exception feature by the rethrow technique:
catch (Exception ex)
{
ErrorHandling.WriteError(ex);
var newEx = new MyException("Additional message", ex) // wrap the original exception instance.
newEx.Data.Add("Exception", "test");
throw newEx;
}
After catching the wrapper exception you can find the original exception in the InnerException property. Another advantage that the original and wrapper exceptions contain their own stack trace so it is easier to find location of error source.

Related

How to catch "A potentially dangerous Request.Path value was detected from the client (:)" to avoid web role crash?

My MVC 5 web application running on Azure Cloud Service crashed with an unhandled exception "A potentially dangerous Request.Path value was detected from the client (:)".
The cause for this crash was some third party (maybe malicious) hit my endpoints with url:
http://myExampleHost.com/m:443/templates
The colon in the url cannot pass the path validation.
Some answers (A potentially dangerous Request.Path value was detected from the client (*)) suggest change the validate rules. However, out of security concerns, we may not want to compromise on this.
The ideal behavior for it that: we catch the exception, log it and return some error messages without crashing. How should we do that?
A more general question on this would be: how to catch an exception before the request hits controllers in MVC?
The ideal behavior for it that: we catch the exception, log it and return some error messages without crashing. How should we do that?
Per my understanding, you could leverage the Application_Error event to capture unhandled exception(s) within ASP.NET. Here is my test, you could refer to it:
protected void Application_Error()
{
HttpContext httpContext = HttpContext.Current;
var exception=Server.GetLastError();
var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);
var jsonResponse = new
{
Message = exception.Message,
StatusCode = httpException.GetHttpCode(),
StackTrace=httpException.StackTrace
};
httpContext.Response.ContentType = "application/json";
httpContext.Response.ContentEncoding = Encoding.UTF8;
httpContext.Response.Write(JsonConvert.SerializeObject(jsonResponse));
httpContext.Response.End();
}
Note: You could also redirect to a specific error page.
Moreover, you could leverage the customErrors in web.config and catch the error page for the specific HTTP error code. Also, you could check the HTTP status code under the Application_EndRequest event and write your custom response, details you could refer to this similar issue. Additionally, I would recommend you follow Demystifying ASP.NET MVC 5 Error Pages and Error Logging for more details about error handling.

WCF "The given key was not present in the dictionary"

I'm getting this error even though I'm not using a Dictionary, and what's weird is that it's when I call the service.
wsSoapClient client = null;
try
{
client = new wsSoapClient();
}
catch (Exception ex)
{
// - Error in the web.config
}
try
{
SendData sendData = new SendData();
sendData.finishDate = myVar.FinishDate;
sendData.startDate = myVar.StartDate;
// - Other fields
// - This lines throw the error below
ClientResult result = client.FinishCourse(sendData);
}
catch (Exception ex)
{
// - Message: The given key was not present in the dictionary.
}
The stack trace:
StackTrace: at System.Collections.Generic.Dictionary``2.get_Item(TKey key)
at Project.Model.CourseService.FinishCourse(XmlNode node)
The service is up to date, and I couldn't find info on this anywhere else. There's two similar questions on SO but they are about Silverlight and I couldn't figure a relation between this (regular C# WCF calling a service) and the solutions.
What causes this and how do I fix it?
(Edit) More Info: The binding is a basicHttpBinding, http only.
Edit²: The WSDL.
Edit³: Found the issue. Apparently, there was already another error (a value larger than the field allows), the service was returning an error but for some reason, WCF didn't take that as error and didn't threw the exception, and I'm guessing it tried to proceed normally, causing this dictionary error since the XML is not what is was expecting.
Assuming your service method is not the one throwing the exception, then it might be the case with the deserialization of the soap message (i.e request object) that happens on the service side.
Check your code(or wsdl) for SendData and see if there are non nullable properties which you are not setting in the request object i.e. sendData object. Missing required properties might cause issues during deserialization.
Posting the code of SendData and\or FinishCourse service method would be great in analyzing the possible issue.

Capturing SOAP faults and handling exceptions

I am consuming a web services. Some methods throw exception when i invoked, because the parameters are invalid values, for example. I want to handle the exceptions but it don't contains any data information, only the message "Bad Request". This is my http response:
try
{
var data = client.SomeMethod(4);
}
catch (Exception exception)
{
// exception.Message = Bad Request
// exception don't contains any more data information
}
How can I capture the other information
You can catch the exception with FaultException when the http status code is 2xx or 5xx, not 4xx. You can catch the http status code 4xx with System.ServiceModel.ProtocolException and then get the stream from the InnerException and parse it or get the FaultException from this stream. See http://blogs.msdn.com/b/nathana/archive/2011/03/31/deciphering-a-soap-fault-with-a-400-status-code.aspx for more details.
I'm assuming this is a WCF web service? You are catching to wide of an exception. Try with a FaultException<TDetail>.
Typical deployed services use the FaultContractAttribute to formally specify all SOAP faults that a client can expect to receive in the normal course of an operation. Error information in a FaultContractAttribute appears as a FaultException (where the typeparameter is the serializable error object specified in the operation's FaultContractAttribute) when it arrives at a client application. The FaultContractAttribute can be used to specify SOAP faults for both two-way service methods and for asynchronous method pairs.
Because FaultException is both a FaultException and therefore a CommunicationException, to catch specified SOAP faults make sure you catch the FaultException types prior to the FaultException and CommunicationException types or handle the specified exceptions in one of those exception handlers.
You can use try-catch like below. Then you can access other information. You have to find the "TDetail". It provides by the web service.
catch(FaultException<TDetail> ex)
{
ex.Code.ToString();
ex.Reason.ToString();
}
Other way.
FaultException faultException = (FaultException)ex;
MessageFault msgFault = faultException.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();

How do I get an HTTP status code from TTransport exceptions?

I'm using a thrift HttpClient (C#) to make web requests to a web server I've set up, and if that server returns something other than 200 (or 202 I imagine), my request throws a TTransport exception.
I'd like to respond to this exception based on the specific status code returned, but I don't see anything that exposes the status code in the exception's interface. Have I missed something? I know the exception message contains the status code, but I'd rather not have to parse that message to get at the status code.
If the server encounters an processing error, the recommended method is not throwing a HTTP 500. Instead, the server should signal this by means of an exception. Consider the following Thrift IDL:
exception MyProcessingError
{
1: string reason
2: string errorDetails
3: string recommendedAction
}
service FooBar {
void ProcessPayments( 1: double amount; 2: string receiver)
throws (1: MyProcessingError mpe)
}
Similar to args and struct fields, multiple exception types can be declared. The client can catch these exceptions as usual:
try
{
client.ProcessPayments( 47.11, "Dagobert");
}
catch (MyProcessingError e)
{
// process exception
}
Remarks
The server may only throw exceptions that are declared in the IDL for
the particular call.
Furthermore, oneway calls never return any value, thus no
exceptions either.

How to handle a exception thrown in c# by a javascript web app?

I'm developing a web application with a client side build with html5 and javascript using, overall, dojo framework (I'm using xhr.post function to communicate with server). The server side is an asmx service in c#.
Here comes the problem: when a webmethod of my service throws an exception:
try
{
throw new Exception("TEST");
}
catch (Exception ex)
{
throw ex;
// TODO: send some info to the client about the error
}
the client is realized than an error has occured and fires the error callback function:
deferred = xhr.post({
url: that.config.urlService,
handleAs: that.config.handleAs,
contentType: that.config.contentType,
postData: that.config.parameters
});
deferred.then(function (res) {
that.success(res);
},
function (err) {
if (that.config.callbackFail) {
that.config.callbackFail(err, that.config.parameters);
}
}
);
But in the 'err' paramater I don't have the exception info, I have the message:
'NetworkError: 500 Internal Server Error - http:/.../Services/Applications/Metrawa/ServiceManagement/WSJob.asmx/Filter'
and inspecting the call to server with firebug, in the response tab I can see strange characters, like if the exception hasn't been serialized.
What I want is to get the exception info in javascript. I've searched some info about this, like to create an own serializable exception class, but it doesn´t work neither. Any solution?
Thanks in advance.
You may opt to handle the exception in your server-side code and send it back as JSON, XML or even String--i.e. something your client can understand.
I would catch the exception server side and always return a valid object with a "Result" property:
eg res.Result (as "OK" or "ERR" etc and handle that on the client)

Categories