Exception thrown from within orElseGet is wrapped with UndeclaredThrowableException - exception

In one of our service classes, we are throwing an exception to deal with in the controller. However, in one of the cases, the exception is from within orElseGet.
def function() throws CustomException {
try {
ProjectAssignment assignment = workspaceRepositoryService.getWorkspaceMembership(command.assigneeEmail, workspaceId).map {
createOrUndelete(it, project, command.assigneeRole, createdBy)
}.orElseGet {
...
try {
Invitation invitation = workspaceService.inviteUserToWorkspace(command.assigneeEmail, workspace, createdBy) // throws CustomException
} catch (Exception e) {
throw e // getting CustomException
}
...
}
} catch(Exception e) {
throw e // getting UndeclaredThrowableException wrapping CustomException
}
}
The exception thrown inside orElseGet is wrapped with UndeclaredThrowableException. Is there a way to preserve the type of thrown exception?

...
catch( UndeclaredThrowableException e){
throw e.getCause()
}
catch(Exception e){
throw e
}

Related

Java 8, Optional. throwing Exceptions, and Re-throwing exceptions, preventing null

I have confusing (lack of comprehension) trying to translate some part of my code to Optional on Java 8.
First example mock Code
private void privateMethodOne(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<CustomResponseDto> responseEntity;
try {
responseEntity = callWebClientRequestOne();
} catch (Exception e) {
RuntimeException ex = new CustomClientException(customRequesDto, e.getMessage());
log.error(ex.getMessage());
throw ex;
}
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
}
In the First example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
How to do the same in a Single line?
Second example mock Code
private void privateMethodTwo(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<byte[]> responseEntity = null;
try {
responseEntity = callWebClientRequestTwo();
} catch (Exception e) {
mapExceptions.put(customRequesDto, e.getMessage());
}
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
// continue the executions
}
Second example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
How to perform the same in a Single line?

Junit test cases for delete operation with try and catch block - handling Exception

public UserNoteDefination deleteByNoteCd (UserNoteDefination request, LogDTO log) {
log.setComponent("ClientRequestService.deleteByNoteCd");
UserNoteDefination response new UserNoteDefination();
String tabllame = request.getTabName();
String noteCd-request.getNoteCd();
if (tabName.equalsIgnoreCase("UND_TABLE"))
{
try
userNoteDefRepository.deleteById(noteCd);
response.setMsg("Completed");
log.setPayload("[FROM:UI] clientRequest:Delete Successfully");
loggingService.log(GuiServiceConstants.INFO LEVEL, log);
}
catch (Exception e){
response.setMsg("Error");
log.setPayload("[FROM:UI] clientRequest:Error occured while delete");
loggingService.log(GuiServiceConstants.ERROR LEVEL, log);
}
return response;
}
This is my junit code in mockito
#Test public void deleteByNoteCd() throws Exception {
LogDTO log = new LogDTO(); log.setComponent("ClientRequestService.getClientRequest");
UserNoteDefination response = new UserNoteDefination();
response.setNoteCd("TEST7");
response.setMsg("Completed");
response.setTabName("UND TABLE");
UserNoteDefination rval - service.deleteByNoteCd(response, log);
assertNotNull(rval);
}
I'm unable to cover the exception part. Cab someone help

How to implement exception handling around MefBootstrapper InitializeModules?

I have some Prism work. Specifically, a bootstrapper (MefBootstrapper) that calls InitializeModules. During one of the modules, an exception is raised, when I re-throw this, I get an exception unhandled.
Unsuccessfully, I have added delegate methods to the exception events, like:
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
System.Windows.Application.Current.DispatcherUnhandledException += CurrentOnDispatcherUnhandledException;
First, you need to mark the exception as handled in the event handler attached to AppDomain.CurrentDomain.UnhandledException to keep the application from crashing:
Application.Current.Dispatcher.UnhandledException += (sender, e) => e.Handled = true;
Second, an exception thrown during a given Prism Module initialization can stop other Modules from loading. To circumvent this you can subclass ModuleManager as follows:
public class ErrorHandlingModuleManager : ModuleManager
{
public ErrorHandlingModuleManager(IModuleInitializer moduleInitializer, IModuleCatalog moduleCatalog, ILoggerFacade loggerFacade) : base(moduleInitializer, moduleCatalog, loggerFacade)
{
}
protected override void LoadModulesThatAreReadyForLoad()
{
var initializationExceptions = new List<Exception>();
while (true)
{
try
{
base.LoadModulesThatAreReadyForLoad();
break;
}
catch (ModuleInitializeException e)
{
initializationExceptions.Add(e);
}
catch (Exception e)
{
initializationExceptions.Add(e);
break;
}
}
if (initializationExceptions.Any())
throw new AggregateException(initializationExceptions);
}
}
}
Be sure to register ErrorHandlingModuleManager with your Mef container to override the the default.

unreported exception IOException; must be caught or declared to be thrown

I have a question , why does java keeps throwing that exception ! Is the problem with the stream ? because I handeled all IOExceptionS !
[[jio0yh.java:12: error: unreported exception IOException; must be
caught or declared to be thrown]]>>
That's the exception that I'm getting!
here is my code
import java.io.*;
public class jio0yh{
public static void main(String[]args){
FileInputStream OD=null;
try{
File f=new File("Binary.dat");
OD= new FileInputStream(f);
byte[]b=new byte[(int)f.length()];
OD.read(b);
for(int i=0;i<b.length;i++)
System.out.println(b[i]);
} catch(FileNotFoundException e){
System.out.println(e.getMessage());
} catch(IOException e){
System.out.println(e.getMessage());
OD.close();
}
}
}
The OD.close(); in your IOException catch block is also susceptible to throwing another IOException.
You should surround the final OD.close() in a finally block:
// ... Any previous try catch code
} finally {
if (OD != null) {
try {
OD.close();
} catch (IOException e) {
// ignore ... any significant errors should already have been
// reported via an IOException from the final flush.
}
}
}
Refer to the following for a more thorough explanation:
Java try/catch/finally best practices while acquiring/closing resources

How to re-throw exception in AspectJ around advise

I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error log and continue the flow by re-throwing the exception.
I tried to achieve this by following but eclipse says "Unhandled Exception type".
Code-against whom AspectJ is to used :-
public interface Iface {
public void reload() throws TException;
public TUser getUserFromUserId(int userId, String serverId) throws ResumeNotFoundException, TException;
public TUser getUserFromUsername(String username, String serverId) throws ResumeNotFoundException, TException;
public TResume getPartialActiveProfileFromUserId(int userId, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException;
public TResume getPartialActiveProfileFromUsername(String username, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException, TException;
}
Code AspectJ :-
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
Object ret;
Throwable ex = null;
StopWatch watch = new Slf4JStopWatch();
try {
ret = proceed();
} catch (UserNotFoundException e) {
ex = e;
throw e;
} catch (ResumeNotFoundException e) {
ex = e;
throw e;
} catch (Throwable e) {
ex = e;
throw new RuntimeException(e);
} finally {
watch.stop(thisJoinPoint.toShortString());
if (ex != null) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
numEx++;
}
}
return ret;
}
}
Please help why this AspectJ is not working.
you can avoid catching the exceptions and just use a try/finally block without the catch.
And if you really need to log the exception you can use an after throwing advice, like this:
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
StopWatch watch = new Slf4JStopWatch();
try {
return proceed();
} finally {
watch.stop(thisJoinPoint.toShortString());
}
}
after() throwing (Exception ex) : call (* com.abc.Iface.* (..)) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
}
}
I'm afraid you cannot write advice to throw exceptions that aren't declared to be thrown at the matched join point. Per: http://www.eclipse.org/aspectj/doc/released/progguide/semantics-advice.html :
"An advice declaration must include a throws clause listing the checked exceptions the body may throw. This list of checked exceptions must be compatible with each target join point of the advice, or an error is signalled by the compiler."
There has been discussion on the aspectj mailing list about improving this situation - see threads like this: http://dev.eclipse.org/mhonarc/lists/aspectj-dev/msg01412.html
but basically what you will need to do is different advice for each variant of exception declaration. For example:
Object around() throws ResumeServiceException, ResumeNotFoundException, TException:
call (* Iface.* (..) throws ResumeServiceException, ResumeNotFoundException, TException) {
that will advise everywhere that has those 3 exceptions.
There is an "ugly" workaround - I found them in Spring4 AbstractTransactionAspect
Object around(...): ... {
try {
return proceed(...);
}
catch (RuntimeException ex) {
throw ex;
}
catch (Error err) {
throw err;
}
catch (Throwable thr) {
Rethrower.rethrow(thr);
throw new IllegalStateException("Should never get here", thr);
}
}
/**
* Ugly but safe workaround: We need to be able to propagate checked exceptions,
* despite AspectJ around advice supporting specifically declared exceptions only.
*/
private static class Rethrower {
public static void rethrow(final Throwable exception) {
class CheckedExceptionRethrower<T extends Throwable> {
#SuppressWarnings("unchecked")
private void rethrow(Throwable exception) throws T {
throw (T) exception;
}
}
new CheckedExceptionRethrower<RuntimeException>().rethrow(exception);
}
}