Created
September 7, 2020 10:28
-
-
Save GrakovNe/1215ac1b644f95e91e50c122f2fce78a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.gene.geneva.module.common.exception; | |
| import com.gene.geneva.module.common.error.ErrorCode; | |
| import java.util.List; | |
| import java.util.Optional; | |
| import java.util.function.Supplier; | |
| import java.util.stream.Collectors; | |
| public class PlatformExceptionUtils { | |
| public static <T> void catchAndRethrow(List<Supplier<T>> actions, Class<? extends PlatformException> exceptionClass) { | |
| var failures = PlatformExceptionUtils.catchFails(actions); | |
| if (!failures.isEmpty()) { | |
| try { | |
| throw exceptionClass.getConstructor(List.class).newInstance(failures); | |
| } catch (ReflectiveOperationException e) { | |
| throw new PlatformException(ErrorCode.INTERNAL_SERVER_ERROR, "Unable to find exception resolver"); | |
| } | |
| } | |
| } | |
| private static <T> Optional<PlatformException> catchFail(Supplier<T> action) { | |
| try { | |
| action.get(); | |
| } catch (PlatformException ex) { | |
| return Optional.of(ex); | |
| } | |
| return Optional.empty(); | |
| } | |
| private static <T> List<PlatformException> catchFails(List<Supplier<T>> actions) { | |
| return actions | |
| .stream() | |
| .map(PlatformExceptionUtils::catchFail) | |
| .filter(Optional::isPresent) | |
| .map(Optional::get) | |
| .collect(Collectors.toList()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment