-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
69 lines (54 loc) · 1.8 KB
/
Copy pathApp.java
File metadata and controls
69 lines (54 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package exception;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.Optional;
public class App {
public static ExceptionUtils eu = new ExceptionUtils();
public static void main(String[] args) {
// Optional<String> ab = Optional.empty();
// String demoThrowException = eu.findOrThrow(ab, new RuntimeException("Demo Throw Exception"));
// System.out.println(demoThrowException);
// Usage:
runWithCatch("sdsdsd", true, () -> {
System.out.println("try body block here~!");
System.out.println(2 / 0);
});
}
public static void runWithCatch(String message, boolean canThrow, CheckedRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
if (canThrow) {
throw new RuntimeException(message, e);
}
// handle once here
System.err.println(e.getMessage());
}
}
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
class ErrorResponse {
private int status;
private String message;
private LocalDateTime timestamp = LocalDateTime.now();
public static ErrorResponse ErrorResponse(String message) {
return ErrorResponse.builder().status(500).timestamp(LocalDateTime.now()).message(message).build();
}
public static String ErrorResponseJson(String message) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(ErrorResponse(message));
}
}
@FunctionalInterface
interface CheckedRunnable {
void run() throws Exception;
}