|
1 | 1 | package io.github.malczuuu.problem4j.core; |
2 | 2 |
|
| 3 | +import java.io.Serial; |
| 4 | + |
3 | 5 | public class ProblemException extends RuntimeException { |
4 | 6 |
|
| 7 | + @Serial private static final long serialVersionUID = 1L; |
| 8 | + |
5 | 9 | private final Problem problem; |
6 | 10 |
|
7 | 11 | public ProblemException(Problem problem) { |
8 | | - super(emptyIfNull(problem.getDetail())); |
| 12 | + super(produceExceptionMessage(problem)); |
9 | 13 | this.problem = problem; |
10 | 14 | } |
11 | 15 |
|
12 | | - private static String emptyIfNull(String str) { |
13 | | - return str != null ? str : ""; |
| 16 | + public ProblemException(String message, Problem problem) { |
| 17 | + super(message); |
| 18 | + this.problem = problem; |
14 | 19 | } |
15 | 20 |
|
16 | 21 | public ProblemException(Problem problem, Throwable cause) { |
17 | | - super(emptyIfNull(problem.getDetail()), cause); |
| 22 | + super(produceExceptionMessage(problem), cause); |
18 | 23 | this.problem = problem; |
19 | 24 | } |
20 | 25 |
|
| 26 | + public ProblemException(String message, Problem problem, Throwable cause) { |
| 27 | + super(message, cause); |
| 28 | + this.problem = problem; |
| 29 | + } |
| 30 | + |
| 31 | + private static String produceExceptionMessage(Problem problem) { |
| 32 | + StringBuilder builder = new StringBuilder(); |
| 33 | + |
| 34 | + if (problem.getTitle() != null) { |
| 35 | + builder.append(problem.getTitle()); |
| 36 | + } |
| 37 | + |
| 38 | + if (problem.getDetail() != null) { |
| 39 | + if (!builder.isEmpty()) { |
| 40 | + builder.append(": "); |
| 41 | + } |
| 42 | + builder.append(problem.getDetail()); |
| 43 | + } |
| 44 | + |
| 45 | + if (problem.getStatus() != 0) { |
| 46 | + if (!builder.isEmpty()) { |
| 47 | + builder.append(" "); |
| 48 | + } |
| 49 | + builder.append("(code: ").append(problem.getStatus()).append(")"); |
| 50 | + } |
| 51 | + |
| 52 | + if (builder.isEmpty()) { |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + return builder.toString(); |
| 57 | + } |
| 58 | + |
21 | 59 | public Problem getProblem() { |
22 | 60 | return problem; |
23 | 61 | } |
|
0 commit comments