Enterprise library exception handling problems with WCF services - exception

my application consists of 3 layers and is very straightforward.
class library with all the business logic
WCF service that exposes the class library
asp.net web UI.
At the class library layer, I have an enterprise library exception handling policy defined so that it logs all exceptions to the database. In the underlying code, exceptions are thrown, and they coalesce up to the facade. In the facade, I trigger the EL policy to log the errors, and then I toggle a sucessStatus boolean in the response and have a method to convert all my exceptions to a friendly list so that the ultimate consumer can dig through this to get any idea of whats going on.
My facade in my class library sort of looks like this:
public SomeResponse DoSomething(SomeRequest request)
{
SomeResponse response = new SomeResponse();
try
{
response.data = SomeOperationThatWillThrowAnException;
}
catch (InvalidOperationException ex)
{
var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
exceptionManager.HandleException(ex, "StandardPolicy");
response.Errors.Add(Utility.ExceptionToError(ex));
response.SuccessStatus = false;
}
return response;
}
If I build a simple winform client and have it talk to my class library, this works.
However when I use the full stack, I get "fault exception was unhandled by user code". I can't seem to configure EL at the WCF layer in any way to keep this from happening.
My WCF service is just a simple wrapper for my class library facade.
public SomeResponse DoSomething(SomeRequest request)
{
return new MyFacade.DoSomething(request);
}
What I want is to have the class library handle the error silently, and not trigger any exceptions at the WCF or UI level. I want the consumer (in this case the ASP.NET webform UI) to have to check the response message contents to get a clue of what happened instead of having an exception stop execution dead in its tracks.

You likely have an error in your configuration file resulting in GetInstance() or HandleException() throwing an exception. Have you tried debugging the WCF service?

Related

How to gracefully handle SoapMessageCreationException?

I am faced with a very tricky scenario, I have a web-service using SOAP 1.2 and I would like to gracefully handle the exception in case a message was sent with SOAP 1.1 header instead of 1.2.
Currently, my messageFactory implementation is SAAJ, and it throws a SoapMessageCreationException when I send 1.1 headers, and my code below does not work and does not catch the error properly:
#Bean
public SoapFaultMappingExceptionResolver exceptionResolver(){
SoapFaultMappingExceptionResolver exceptionResolver = new DetailSoapFaultDefinitionExceptionResolver();
SoapFaultDefinition faultDefinition = new SoapFaultDefinition();
faultDefinition.setFaultCode(SoapFaultDefinition.SERVER);
exceptionResolver.setDefaultFault(faultDefinition);
Properties errorMappings = new Properties();
errorMappings.setProperty(Exception.class.getName(), SoapFaultDefinition.SERVER.toString());
errorMappings.setProperty(ServiceFaultException.class.getName(), SoapFaultDefinition.SERVER.toString());
exceptionResolver.setExceptionMappings(errorMappings);
exceptionResolver.setOrder(1);
return exceptionResolver;
}
I took the example from https://memorynotfound.com/spring-ws-add-detail-soapfault-exception-handling/ however it does not seem to work in my case.
The only approach I have found that works is How to return custom SOAP Error from Spring Boot Endpoint Service? which to be is very much an overkill.
If anyone has come across this issue before, I would love some pointers!

ConnectionFactory exception Camel testing JMS

I'm doing my first steps with Camel and currently working on writing a simple junit test using jms as a transport.
Here is a code I wrote:
public class FirstMockTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("jms:topic:quote")
.to("mock:quote");
}
};
}
#Test
public void testMessageCount() throws InterruptedException {
MockEndpoint mockEndpoint = getMockEndpoint("mock:quote");
mockEndpoint.setExpectedMessageCount(1);
template.sendBody("jms:topic:quote", "Camel rocks");
mockEndpoint.assertIsSatisfied();
}
}
Because of missing connectionFactory I got the following exception:
org.apache.camel.FailedToCreateRouteException: Failed to create route route1: Route(route1)[[From[jms:topic:quote]] -> [To[mock:quote]]] because of connectionFactory must be specified
I'm able to fix it adding the following lines to my route:
ConnectionFactory connectionFactory =
new ActiveMQConnectionFactory("vm://localhost?roker.persistent=false");
context.addComponent("jms", JmsComponent.jmsComponent(connectionFactory));
But I don't like I'm adding some components to my context inside the route. Also, If i want to have another route I will need to do it again.
Obviously, there should be another way to tell my test about connection factory.
Thank you in advance!
It's a good idea to define the JMS connection factory outside of your Camel context and, if possible, reuse it. How to do that depends on your component model / execution environment.
If you're using a Java SE version that supports CDI, that would be an obvious choice. You'd define your JMS connection factory as a named component once and inject it everywhere you need it. Have a look at http://camel.apache.org/cdi.html and for testing support at http://camel.apache.org/cdi-testing.html
If you're using Spring, define your connection factory as a spring bean and inject it wherever you need it.
If you're using Java EE on an application server, you'd usually define the JMS connection factory using the mechanisms of that app server. You'd then look up the JMS connection factory using JNDI.
If you're running in an OSGi container, you should define the JMS connection factory in its own bundle and export it as an OSGi service. In the bundle of your Camel context, import that OSGi servide and inject it into the Camel context.
In all above cases you should consider using a pooled JMS connection factory.
For CDI, Spring and OSGi, have a look at: http://activemq.apache.org/maven/5.14.5/apidocs/org/apache/activemq/jms/pool/PooledConnectionFactory.html
For Java EE the way how to set pooling parameters depends on your app server.
Note of caution: for Java SE CDI and Spring there should be only one Camel context per application (you can have many routes, though). So if the JMS connection factory is only used in that one Camel context, there is not much reuse. Despite that I still think it's preferable to define the JMS connection outside of the Camel context in a separate component. It's, well, cleaner.
Since you are writing a junit you can avoid creating a ConnectionFactory if you stub the jms endpoint. You can name the endpoint as stub:jms:topic:quote. Have a look at sample example at link https://github.com/camelinaction/camelinaction2/blob/master/chapter9/mock/src/test/java/camelinaction/FirstMockTest.java

Programmatically instantiate a FeignClient for tests

I have a dead simple FeignClient interface that I would like to "unit"/integration test with a fake HTTP server, WireMock for example. The idea is to test the mapping with a sampled HTTP API response, without configuring a whole Spring Boot/Cloud Context.
#FeignClient(name = "foo", url = "${foo.url}")
public interface FooClient {
#RequestMapping(value = "/foo/{foo-id}/bar", method = RequestMethod.GET)
public Bar getBar(#PathVariable("foo-id") String fooId);
}
Is there any way to programmatically instantiate this interface, like a Spring Data Repository through a *RepositoryFactoryBean ?
I see a FeignClientFactoryBean in the source code, but it is package protected, and it relies on an ApplicationContext object to retrieve its dependencies anyway.
Well, you can fake a real rest client using wiremock for testing purposes, but this is more about containing the functional test, that feign clients themself work. This is mostly not what you really want to test, because the actual need is to test your components using your client behave in a specified way.
The best practice for me is not to make live hard with maintaing a fake server, but mock the clients behavior with Mockito. If you use Spring Boot 1.4.0, here is the way to go:
Consider you have some FooBarService, which internally uses your FooClient to peform some FooBarService::someAction(String fooId), which performs some business logic which needs to work with a foo with given id
#RunWith(SpringRunner.class)
#SpringBootTest(classes = App.class)
class FooUnitTest {
#Autowired;
private FooBarService fooBarService;
#MockBean;
private FooClient fooClient;
#Test
public void testService() {
given(fooClient.getBar("1")).willReturn(new Bar(...));
fooBarService.someAction("1");
//assert here, that someAction did what it supposed to do for that bar
}
}
At this point you first should clarify, what you expect the REST client to respond, when asking for "/foo/1/bar", by creating a mock for exactly that case and give the Bar object you expect to receive for that API, and assert that your application is in the desired state.

Mule: JUnit test case to call a service which is in middle of the Mule flow

I'm newbie for JUnit test case. Please help me on this issue. I have 2 mule flows- first flow having MQ as inbound and it has datamapper to transformer the xml. With the first flow input, i'm calling second flow where we are calling the existing service ( SOAP/HTTP) call. Please find my JUnit below. I'm able to get the success response. But my requirement
1. I need to see the transformer response coming out from the Transformer.( Like how we see via logger component in our flow)
2.Need to override the url (HTTP) through JUnit ( in order to test the error scenario)
public class Request_SuccessPath extends FunctionalTestCase {
#Test
public void BulkRequest () throws Exception {
MuleClient client = muleContext.getClient();
System.out.println("test");
String payload = " <root> <messageName>str1234</messageName><messageId>12345</messageId><DS>123</DS><</root>";
MuleMessage reply = client.send ("vm://test",payload ,null);}
#Override
protected String getConfigResources() {
// TODO Auto-generated method stub
return "src/main/app/project.xml";}
i thought the following snippet will override the url.But it is not
DefaultHttpClient client1 = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:7800/service);
assertNotNull(response);
3. How to take the control of the flow and see any response inbetween the flow.
Instead of WMQ, i have replaced VM as inbound end point for testing purposes.
4. Is there any chance like without replacing VM can we call directly with WMQ through JUnit TestCase. Kindly help me on this.
I'm using 3.4 version, not using maven as of now. Please help me. Thanks in advance.
1) What do you mean by "see". Would it work logging it? inspecting it while debugging?
2) You should parametrize your endpoint with a variable, something like
and configure a property placeholder as explained here: http://www.mulesoft.org/documentation/display/current/Using+Parameters+in+Your+Configuration+Files
Adding http.port, http.host and http.path variables to mule-app.properties
taking into account that you must set system-properties-mode="OVERRIDE" and then start your Mule server using bin/mule -M-Dhttp.host=your-host -M-Dhttp.port=your-port -M-Dhttp.path=your-path
3) Yes, WMQ has a Java API you can use to interact with it: http://publib.boulder.ibm.com/infocenter/wmqv6/v6r0/index.jsp?topic=%2Fcom.ibm.mq.csqzaw.doc%2Fuj41013_.htm , you will probably found hundreds of examples by googling about it.
Regards.

WCF Exception Handling Strategies

We are developing a proxy in WCF that will serve as a means of communication for some handhelds running our custom client application. I am curious what error handling strategies people use as I would rather not wrap EVERY proxy call in try/catch.
When I develop ASP .NET I dont catch the majority of exceptions, I leverage Application_Error in Global asax which can then log the exception, send an email, and redirect the user to a custom error landing page. What I am looking for in WCF is similar to this, except that it would allow me to pass a general faultreason to the client from a central location.
Basically I am curious how people centralize their exception handling in WCF apps.
Thanks
You might find the IErrorHandler interface useful here. We've been using this to do pretty much what you mention - centralised exception logging and providing generalised fault reasons without having to litter the code with numerous try/catches to try and deal with the problem locally.
So here is what I did. We have a few custom exceptions in our application such as BusinessRuleException and ProcessException, WCF supports both FaultException and FaultException<T>.
General practice seems to be that you always throw FaultException to the client in the case of a general error or an error that you dont want to display exactly what happened. In other cases you can pass FaultException<T> where T is a class with information about the particular exception.
I created this concept of Violations in the application, which basically meant that any custom exception had a property containing the corresponding Violation instance. This instance was then passed down to the client enabling the client to recognize when a recoverable error had occured.
This solved part of the problem, but I still wanted a general catch all that would allow me to centeralize logging. I found this by using the IErrorHandle interface and adding my own custom error handler to WCF. Here is the code:
public class ServiceHostGeneralErrorHandler : IErrorHandler
{
public void ProvideFault(Exception ex, MessageVersion version, ref Message fault)
{
if (ex is FaultException)
return;
// a general message to the client
var faultException = new FaultException("A General Error Occured");
MessageFault messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, null);
}
public bool HandleError(Exception ex)
{
// log the exception
// mark as handled
return true;
}
}
Using this method, I can convert the exception from whatever it is to something that can be easily displayed on the client while at the same time logging the real exception for the IT staff to see. So far this approach is working quite well and follows the same structure as other modules in the application.
We use the Exception Handling Application block and shield most faults from clients to avoid disclosing sensitive information, this article might be a good starting point for you, as with "best practices" - you should use what fits your domain.