How to use exception mapper for exceptions thrown from interceptors in MSF4J - msf4j

I added a authorisation module in interceptor, and tried to use exception mapper to throw 401 status code, but even if it is scanning my exception mapper, it is not using it in runtime.
#Component
public class ExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> {
public ExceptionMapper() {
System.out.println("true Manish= " + true);
}
#Override
public Response toResponse(Exception exception) {
System.out.println("product Manish Exception comning here");
return Response.status(Response.Status.EXPECTATION_FAILED).
entity(exception.getMessage()).
type("text/plain").
build();
}
}
So, it is printing true Manish=true, but when my interceptor throws an exception, it doesn't hit toResponse() method

At the moment MSF4J can't map the exception which are get thrown from interceptor level. It only can map the exceptions which are thrown inside the actual service. We would like to enhance that to having global exception mappers. https://github.com/wso2/msf4j/issues/327 been created for that.

Related

Should we handle dataAccessException and jdbc exception in springboot in production?

public UserMailDto getUserByEmail(String email) throws UserExceptionMessage {
try {
return userRepository.searchByMail(email);
} catch (DataAccessException | JDBCConnectionException accessException) {
com.example.user_service.config.log.Logger.errorLog("UserService", accessException.getMessage());
throw new DataAccessExceptionMessage(Messages.ERROR_TRY_AGAIN + accessException.getMessage());
}
}
In my view you should handle it, but not with a try..catch block in what seems to be your service. Why are you catching the Exception and then rethrowing you own custom Exception with a message? You will need to handle that Exception at some point in your code to. So you are not really handling it here.
It looks like you are building a web app, so I would recommend that you handle your Exceptions in one central place in a #ControllerAdvice class. You can read about it here. This way you can really handle the Exception, by returning a corresponding status code to the user. 503 in your case.

ASPNETCore API ExceptionFilterAttribute and IStringLocalizer

I have a ExceptionFilterAttribute in my ASPNETCore API where I handle certain exception types.
For example any UnauthorizedAccessException I return HttpStatusCode.Unauthorized, any KeyNotFoundException I return HttpStatusCode.NotFound etc.
However, I'm also returning a basic message. For example, the string "Key Not Found" is returned with the HttpStatusCode.NotFound.
I would like the messages contained in the ExceptionFilterAttribute to be parsed using the IStringLocalizer. However, a ExceptionFilterAttribute doesn't seem to support dependency injection.
Has anyone encountered the same issue?
Is there an approach here which is considered best practice?
You can access the IServiceProvider from the ExceptionContext.
public override void OnException(ExceptionContext context)
{
var service = context.HttpContext.RequestServices.GetService<MyService>();
}

NServiceBus 6: want some errors to ignore eror queue

As per Customizing Error Handling "Throwing the exception in the catch block will forward the message to the error queue. If that's not desired, remove the throw from the catch block to indicate that the message has been successfully processed." That's not true for me even if I simply swallow any kind of exception in a behavior:
public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
{
try
{
await next().ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
I put a breakpoint there and made sure execution hit the catch block. Nevertheless after intimidate and delayed retries messages inevitably ends up in error queue. And I have no more Behaviours in the pipeline besides this one.
Only if I run context.DoNotContinueDispatchingCurrentMessageToHandlers(); inside the catch block it prevents sending error to the error queue, but it also prevents any further immediate and delayed retries.
Any idea on why it works in contravention of Particular NserviceBus documentation is very appreciated
NserviceBus ver. used: 6.4.3
UPDATE:
I want only certain type of exceptions not being sent to an error queue in NServiceBus 6, however to make test case more clear and narrow down the root cause of an issue I use just type Exception. After throwing exception, execution certainly hits the empty catch block. Here is more code to that:
public class EndpointConfig : IConfigureThisEndpoint
{
public void Customize(EndpointConfiguration endpointConfiguration)
{
endpointConfiguration.DefineEndpointName("testEndpoint");
endpointConfiguration.UseSerialization<XmlSerializer>();
endpointConfiguration.DisableFeature<AutoSubscribe>();
configure
.Conventions()
.DefiningCommandsAs(t => t.IsMatched("Command"))
.DefiningEventsAs(t => t.IsMatched("Event"))
.DefiningMessagesAs(t => t.IsMatched("Message"));
var transport = endpointConfiguration.UseTransport<MsmqTransport>();
var routing = transport.Routing();
var rountingConfigurator = container.GetInstance<IRountingConfiguration>();
rountingConfigurator.ApplyRountingConfig(routing);
var instanceMappingFile = routing.InstanceMappingFile();
instanceMappingFile.FilePath("routing.xml");
transport.Transactions(TransportTransactionMode.TransactionScope);
endpointConfiguration.Pipeline.Register(
new CustomFaultMechanismBehavior(),
"Behavior to add custom handling logic for certain type of exceptions");
endpointConfiguration.UseContainer<StructureMapBuilder>(c => c.ExistingContainer(container));
var recoverability = endpointConfiguration.Recoverability();
recoverability.Immediate(immediate =>
{
immediate.NumberOfRetries(2);
});
endpointConfiguration.LimitMessageProcessingConcurrencyTo(16);
recoverability.Delayed(delayed =>
{
delayed.NumberOfRetries(2);
});
endpointConfiguration.SendFailedMessagesTo("errorQueue");
...
}
}
public class CustomFaultMechanismBehavior : Behavior<IInvokeHandlerContext>
{
public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
{
try
{
await next().ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
}
UPDATE 2
I think I know what's going on: message is handled by first handler that throws an exception which is caught by the Behavior catch block, but then NServiceBus runtime tries to instantiate second handler class which is also supposed to handle the message (it handles class the message is derived from). That's where another exception is thrown in a constructor of one of dependent class. StructureMap tries to instantiate the handler and all its dependent services declared in the constructor and in the process runs into the exception. And this exception is not caught by CustomFaultMechanismBehavior.
So my I rephrase my question now: Is there any way to suppress errors (ignore error queue) occurring inside constructor or simply during StructureMap classes initialization? Seems like the described way does not cover this kind of situations
Your behavior is activated on Handler invocation. This means you are catching exceptions happening inside the Handle method so any other exception, e.g. in the Constructor of the handler would not be caught.
To change the way you 'capture' the exceptions, you can change the way the behavior is activated, e.g. change it from Behavior<IInvokeHandlerContext> to Behavior<ITransportReceiveContext> which is activated when the transport receives a message. You can investigate on different stages and behaviors to see which one suits your purpose best.

Camel: exception in message listener is not GETTING HANDLED back in camel route

I have a camel route with exception handling capability, and also a defaultmessagelistener where it consumes the message from amq endpoint form camel route.
when an exception is thrown in the messageListener onMessage(Message message) it is not routing back to camel where i handle exceptions
onException(Throwable.class)
.process(customErrorHandler);
Expected: on throwing exception in messagelistener come back to route and porcess errorHandler
Actual: catching the exception
#Override
public void onMessage(Message message) {
try {
//dosomething which throws an exception
} catch (Exception e) {
//send back to camel route how??????
onException(Throwable.class)
.process(customErrorHandler);
}
}
Thank you in advance
just don't catch the Exception in your onMessage() method...let it propagate back up. if that onMessage is invoked by a Camel route...then it should hit your Camel route's onException() clauses, etc.

Ninject Interceptors

I'm developing a WPF desktop application with caliburn.micro framework, and I want to configure ninject interceptors so that I can intercept method calls. I would like to do this to handle exceptions in a centralized place, so that I don't have many try-catch blocks everywhere around my code.
I haven't been able to acomplish this, because everytime I wire everything up with ninject, the system throws an exception.
So here's some code:
The AppBootstrapper configure method looks like this:
protected override void Configure()
{
_kernel = new StandardKernel(new NinjectServiceModule());
_kernel.Bind<IWindowManager>().To<WindowManager>().InSingletonScope();
_kernel.Bind<IEventAggregator>().To<EventAggregator>().InSingletonScope();
_kernel.Bind<ISomeViewModel>().To<SomeViewModel>().Intercept().With<SomeInterceptor>() //this is where the exception is thrown;
_kernel.Bind<IShell>().To<ShellViewModel>();
}
Now the intercept method in my interceptor:
public void Intercept(IInvocation invocation)
{
if (invocation.Request.Method.Name == "TheMethodIWantIntercepted")
{
try
{
invocation.Proceed();
}
catch (Exception)
{
Console.WriteLine("I Handled exception");
}
}
else
{
invocation.Proceed();
}
}
The method in the view model looks like this:
public virtual void TheMethodIWantIntercepted()
{
//Some logic here
}
So that's how interceptors are supposed to work. But it doesn't work, everytime I run the program, and ninject tries to inject the instance of SomeViewModel into ISomeViewModel, the program execution fails, and this is the exception that is thrown (and the stack trace):
http://pastebin.com/qerZAjVr
Hope you can help me with this, thank you in advance.
You have to load either DynamicProxy(2)Module or LinFuModule depending on what proxy library you prefer.
Also be aware that Ninject 2.2 will create a class proxy for SomeViewModel which requires:
a parameterless constructor
virtual methods
Interface proxies don't have this restriction but this requires Ninject 3.0.0