Exception Handling in REST - rest

I have created a REST service using WCF for communicating with BLL/DAL from UI. Now, I would like to implement Exception Handling through some globalize way in REST. I am using HTTPClient to communicate with REST from client. The following are the ways, I have implemented exception handling:
Approach 1:
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.Unauthorized;
response.StatusDescription = ex.Message;
success = false;
Approach 2:
throw new WebProtocolException(HttpStatusCode.NotFound, ex.Message, null);
but somehow I am not able to catch them in the client side. Kindly suggest some pointers in order to handle exceptions raised by service globally.
I am throwing WebProtocolException (Approach 2) along with error code and error message from the service to UI in order to notify users about the exception. I am able to receive the error code in UI side but not getting error message or detail.
Then I created another service (having .svc extension) and added following line to the service's markup: "Factory='Microsoft.ServiceModel.Web.WebServiceHost2Factory'". Now, I am able to receive the error message along with error code on client side (UI).
Can anybody let me know how to use the WebServiceHost2Factory method in my existing service which is a class file instead of .svc file?
Any suggestions will be highly appreciated. Thanks

HttpClient does not throw exceptions when a response comes back that is not "successful". If you really want exceptions to be thrown on the client side, then call
response.EnsureResponseIsSuccessful();
Otherwise, just check the status code on the client and decide what to do based on that value.
You cannot throw exceptions on the server and expect the exceptions to be propagated to the client. HTTP does not have any notion of exception.

Related

Flutter/Dart + gRPC Stream error: Stream was terminated by peer (errorCode: 2)

I'm having this intermittent error come up when making a call from a Dart gRPC client to a Go gRPC server. The exact error message is:
gRPC Error (code: 2, codeName: UNKNOWN, message: HTTP/2 error: Stream
error: Stream was terminated by peer (errorCode: 2)
This seems to occur frequently on creating the client stub with the channel and making a call to the server. Subsequent calls seems to work fine with a response returned correctly to the client. Then this error intermittently pops up again every n-th call (could be after 5 calls, 10 calls sometimes no errors until the 20th call).
When I use a different client (eg: BloomRPC or Java app I wrote), this does not happen no matter how hard or fast I spam the calls to the server. This kind of implies the server is probably not the issue.
Can anyone shine a light on what might be happening? Or provide some hints as to where to start looking/debugging? I've tried stepping through the code, but not really able to follow what is happening when the gRPC call is made/returned.
Steps in the client code:
create ClientChannel with ip, ports
final cc = ClientChannel(serverIP,
port: serverPort,
options:
const ChannelOptions(credentials: ChannelCredentials.insecure()
));
created a stub based on above channel
_userQueryStub = UserQueryGRPCClient(cc,
options: CallOptions(timeout: Duration(seconds: 30)));
call function from stub (repeatedly)
GetUserInformationRequest request = GetUserInformationRequest(userId: userId);
GetUserInformationResponse response = await _userQueryStub.getUserInformation(request);
Any help will be greatly appreciated!

Throw SOAP exception when there are pending Entity Framework database migrations for any SOAP request

I want to throw a SOAP exception when there are pending Entity Framework migrations and someone sends any SOAP request. If I throw a FaultException within my Global.asax, I get a html response from the IIS. This works but it is rather ugly. So I tried to throw it within the IServiceBehavior.Validate() method of my ServiceBehavior class.
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
var isDatabaseUpdateRequired = new MyDb().GetPendingMigrations().Any();
if (isDatabaseUpdateRequired) throw new FaultException("There are pending migrations.");
}
But I do not get any XML response with the error message on my SoapUI client. Where should I throw this exception?
You can throw this exception in a class that implements the interface IDispatchMessageInspector. Implement IDispatchMessageInspector to inspect or modify inbound or outbound application messages either prior to dispatching a request message to an operation or before returning a reply message to a caller.
When the server receives the client request, the DispatchMessageInspector intercepts all the client requests.
The picture above is the implementation of IDispatchMessageInspector, Throw an exception in the BeforeSendReply method.
The client sends a request to the server and gets an exception message.
Here is a link about the IDispatchMessageInspector interface.

Intercept/Callback for QuickFIX message

I am using a FIX protocol to communicate with one of our counterparties. I have used Camel with Spring to build my communication routes.
I have a requirement where in my counterparty is expecting an ACK for every request it sends to me.
For example:
TradeCaptureRequestAck in response to TradeCaptureRequest
AllocationReportAck in response to AllocationReport
Confirmation_Ack in response to Confirmation
They are expecting a response irrespective of what happens at our end (even if something fails or exception occurs).
One way I know we can intercept the incoming message via MessageFactory. We can create a custom messagefactory and inject it in while creating QuickFixJComponent bean.
Problem with this approach is at factory level I will just be able to get the message type like TradeCaptureReport, AllocationReport etc. but not the content because factory only creates (and returns) the appropriate Message object. Actual work of populating this message object with incoming message data happens in Session class I guess (not sure about this).
Can someone please tell me if there is a way I can get or intercept the request message as soon as it reaches the route so that I can send the appropriate ACK to counterparty?

how to handle HTTP errors in emberJs while using ember-data with RESTAdapters?

I have a route /products. In App.ProductsRoute, I am using a setupController hook to assign list of products fetched from server to local App.Product objects.
I am setting the model in setupController hook as :
self_controller.set('model', self_controller.store.find('product'));
This works well when HTTP status is 200. But when server returns some HTTP error (like 500-Internal Server Error, 401-Unauthorized Errors, etc) I am getting error as JSON.parse. I am not sure how to handle errors for this.store.find() calls.
Note: It returns Ember's promiseArray which I need to check once resolved (before actually assigning it to model). Any help on this topic would be much appreciated. Thanks.
What about using the promise's catch callback to handle the errors? Untested, but something like this should work:
self_controller.store.find('product').then(function(products) {
self_controller.set('model', products);
}).catch(function(reason) {
// Do something to handle the error response...
});

Zend framework- how to stop execution and redirect to the error controller

I want to catch php errors so i used set_error_handler('handler_function') when i echo the error message , 'Zend_Controller_Response_Exception' with message 'Cannot send headers; headers already sent' is thrown when i used the following lines
$fc=Zend_Controller_Front::getInstance();
$fc->getResponse()->setBody($error);
an error happened 'call to setBody method of a non-object'
i tried to throw an exception from the error handler but this depend on the error occurring before bootstrapping is displayed directly after bootstrapping displayed in errorController
i used $fc->throwExceptions(false) to ensure it will send exceptions to error controller
when i do nothing in the error handler the execution is continued
what i need is to have one place to handle all errors
if there is a way to redirect to the error controller with error in params this will be good
IMO best way to handle these errors is to register error handler that will convert any error/fatal error to exception. I guess that response is not created yet. You have to use $fc's setResponse() method to create new response. I would guess that converting to exception should work in any case. Same as exceptions from Zend classes work.