Exception the exception thrown from Stream.forEach() in ControllerAdvice - spring-mvc

In my Spring MVC Based application, I have a ControllerAdvice defined.
Now, in one of my service classes, I have this parallelStream created:
rawImportList.parallelStream().forEach(rawImportBatch -> {
rawImportBatch.parallelStream().forEach(this::importNominationFromRawImport)
});
The importNominationFromRawImport() method here, by definition, could throw a custom exception that should ideally be handled in the ControllerAdvice.
What could be the best way to achieve this?

Related

Does Spring override try catch in the controller class with the SimpleExceptionResolver

I am planning to use SimpleExceptionResolver for handling most generic exceptions like unhandled runtime exceptions. e.g. NullPointerException, NumberFormatException etc. and wil redirect to common error jsp
However in the controller I would catch the application specific exceptions like custom exceptions.
My question is :
Lets say if SimpleExceptionResolver is configured to catch the Exception class, will it override the controller level catch stattements and catch all the excptions instead. My guess is, SimpleExceptionResolver does not give opportunity to the Controller class to handle any custom exception.
Kindly provide valuable suggestions and workarounds thnks
If you are using try catch(Exception e) block,in your controller,that means you are already handling the exception,inside your controller classes.It will not be handled by HandlerExceptionResolver class.Only those exception which can not be caught inside the controller are propagated to HandlerExceptionResolver.
I would suggest in case of exception in your controller classes,you can use try catch block,and from catch block you can throw your own custom exception,which will be propagated to SimpleMappingExceptionResolver,and there you can prepare response message as per the exception type and cause.

Advice on exception handling in webservice

I need some advice on a good exception handling strategy in my webservice.
My web service methods are doing the standard CRUD operations against an Oracle database. Therefore, I have some methods that select data and return a dataset and others that do either an insert/update/ or delete and don't return anything.
Initially, I had all my code in each webservice method in a try-catch-finally catching an Oracle exception. I read some articles on the web that says this is not good and I should only surround something in try-catch if there is a potential for an exception. Now I am thinking that maybe it would be best if I put only my Insert/Update/Delete methods in try-catch-finally blocks.
So my questions are:
Should I put all my methods in try-catch-finally? They all interact with Oracle and could potentially cause an exception. Or should I only do this for the Insert/Update and Delete methods?
I don't really have any requirements on what they want to happen when an exception does occur. I am just going on common sense. I know that they definitely don't want the app to end. I am planning on logging the exception in some manner and re-throwing it to the client. I am doing this when there is an Oracle Exception.
Basically you need to do try-catch on every WebMethod. Since the event won't bubble up, I think there is no other better way.
However, you can use the trick in this post to make your life easier.
The way he does is creating a utility method like this and invoke that method by passing it a delegate to your web method logic.
private T Execute<T>(Func<T> body)
{
//wrap everything in common try/catch
try
{
return body();
}
catch (SoapException)
{
//rethrow any pre-generated SOAP faults
throw;
}
catch (ValidationException ex)
{
//validation error caused by client
ClientError innerError = new ClientError();
//TODO: populate client error as needed
//throw SOAP fault
throw this.GenerateSoapException(
"An error occurred while validating the client request.",
SoapException.ClientFaultCode,
innerError);
}
catch (Exception ex)
{
//everything else is treated as an error caused by server
ServerError innerError = new ServerError();
//TODO: populate server error as needed
//TODO: log error
//throw SOAP fault
throw this.GenerateSoapException(
"An unexpected error occurred on the server.",
SoapException.ServerFaultCode,
innerError);
}
}
I assume you are using ASP.NET WebMethods. My advice is that you always catch exceptions on the service layer, write a log and throw a SoapException. Basically you can try-catch on each service method (WebMethod). If you fail to do so, you would be exposing exception details to the client calling the service and that could be a potential security issue.

Propagating AccessDeniedException in Spring Security

In my web application I am using Spring Security and Spring MVC.
I have secured a couple of methods with #Secured annotation and configured Spring Security in such a way that when one of those methods is accessed without the proper role, the user is taken to the login page. However, I do not want that behaviour when the offending request comes from Ajax, so I implemented the custom #ExceptionHandler annotated method to determine the request's context.
This is my exception handler:
#ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(AccessDeniedException ex, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (isAjax(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
throw ex;
}
}
This way I can both handle the exception myself (for example, log an attempt of accessing the #Secured method) and then let Spring do its part and redirect the user to the login page by rethrowing the AccessDeniedException. Also, when the request comes from Ajax I set the response status to SC_UNAUTHORIZED and handle the error on the client side.
Now, this seems to be working fine, but I am getting the following ERROR each time I rethrow the exception from the handleAccessDeniedException method:
ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke #ExceptionHandler method: public void app.controller.BaseController.handleAccessDeniedException(org.springframework.security.access.AccessDeniedException,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception
org.springframework.security.access.AccessDeniedException:
at app.controller.BaseController.handleAccessDeniedException(BaseController.java:23)
at app.controller.BaseController$$FastClassByCGLIB$$8f052058.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
(...)
I have not added any exception handling specifics to spring xml configuration files.
I do not see any issues with the app itself, but the error is there and since I am quite new to Spring MVC and Spring Security, I am guessing that I am not doing this properly. Any suggestions? Thanks!
Your exception handler isn't supposed to throw another exception. It's supposed to deal with it and send a response. It's a good idea to check the code if you get an error from a class to see how it behaves.
For the non-ajax case, you'd be better to redirect the response to the login page, if that's what you want. Alternatively, you can customize the AuthenticationEntryPoint used by Spring Security instead and omit AccessDeniedExceptions from MVC handling. The behaviour would essentially be the same as the defaul LoginUrlAuthenticationEntryPoint but you would extend it to return a 403 when an ajax request is detected.

Spring MVC: global exception handler

I want to implement some kind of global event handler but only for error logging purpose and without any redirection.
For example, the controller's method fails and my event handler will catch the exception (of any kind or specific type of exception) and does some logic and that's it. After that the controller's logic will continue. I checked the ExceptionHandler but it requires to return Model/Map or handle the response so it doesn't help me.
Is it possible?
Thank you
Have you ever considered AOP for your requirement ? Use - After Throwing Advice.

Need parameter values of method where exception is thrown for logging without specific code in each method

How do I get current parameter values when an exception occurs inside a random method without having specific code in each method to write out the values?
I need this for ASP.NET MVC and WCF IErrorHandler?
For example given the following code:
public void SomeRandomMethod(Request request, string someRandomString)
{
throw new Exception();
}
is there a way for an IErrorHandler in WCF or MVC global.asax HttpApplication's Application_Error & Elmah to get the value of the Request object and someRandomString without specifically catching the exception and writing custom logic for each of N number of methods then throwing again?
Maybe this should be broken into 2 questions one for WCF and one for ASP>NET MVC?
The request hierarchies seem very similar to me and so I was hoping for a single unified answer.
I would recommend using Elmah. It's a wonderful logging tool for ASP.NET applications. It will include the parameters passed along with the HTTP request.

Resources