Skip to content

Commit

Permalink
#126: UncheckedBytes with fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Jun 14, 2017
1 parent 2e988e9 commit 2f19da6
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions src/main/java/org/cactoos/io/UncheckedBytes.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.io.IOException;
import java.io.UncheckedIOException;
import org.cactoos.Bytes;
import org.cactoos.Func;
import org.cactoos.func.UncheckedFunc;

/**
* Bytes that doesn't throw checked {@link Exception}.
Expand All @@ -43,21 +45,45 @@ public final class UncheckedBytes implements Bytes {
*/
private final Bytes bytes;

/**
* Fallback.
*/
private final Func<IOException, byte[]> fallback;

/**
* Ctor.
* @param bts Encapsulated bytes
*/
public UncheckedBytes(final Bytes bts) {
this(
bts,
error -> {
throw new UncheckedIOException(error);
}
);
}

/**
* Ctor.
* @param bytes Encapsulated bytes
* @param bts Encapsulated bytes
* @param fbk Fallback
* @since 0.5
*/
public UncheckedBytes(final Bytes bytes) {
this.bytes = bytes;
public UncheckedBytes(final Bytes bts,
final Func<IOException, byte[]> fbk) {
this.bytes = bts;
this.fallback = fbk;
}

@Override
public byte[] asBytes() {
byte[] data;
try {
return this.bytes.asBytes();
data = this.bytes.asBytes();
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
data = new UncheckedFunc<>(this.fallback).apply(ex);
}
return data;
}

}

0 comments on commit 2f19da6

Please sign in to comment.