1 /*
2 * SPDX-FileCopyrightText: none
3 * SPDX-License-Identifier: CC0-1.0
4 */
5
6 package gov.nist.secauto.metaschema.core.metapath;
7
8 import edu.umd.cs.findbugs.annotations.Nullable;
9
10 /**
11 * This Metapath exception base class is used for all exceptions that have a
12 * defined error code family and value.
13 */
14 public abstract class AbstractCodedMetapathException
15 extends MetapathException {
16
17 /**
18 * the serial version UID.
19 */
20 private static final long serialVersionUID = 1L;
21
22 /**
23 * The error code.
24 */
25 private final int code;
26
27 /**
28 * Constructs a new Metapath exception with the provided {@code code},
29 * {@code message}, and no cause.
30 *
31 * @param code
32 * the error code value
33 * @param message
34 * the exception message
35 */
36 public AbstractCodedMetapathException(int code, String message) {
37 super(message);
38 this.code = code;
39 }
40
41 /**
42 * Constructs a new Metapath exception with the provided {@code code},
43 * {@code message}, and {@code cause}.
44 *
45 * @param code
46 * the error code value
47 * @param message
48 * the exception message
49 * @param cause
50 * the original exception cause
51 */
52 public AbstractCodedMetapathException(int code, String message, Throwable cause) {
53 super(message, cause);
54 this.code = code;
55 }
56
57 /**
58 * Constructs a new Metapath exception with a {@code null} message and the
59 * provided {@code cause}.
60 *
61 * @param code
62 * the error code value
63 * @param cause
64 * the original exception cause
65 */
66 public AbstractCodedMetapathException(int code, Throwable cause) {
67 super(cause);
68 this.code = code;
69 }
70
71 @Override
72 public String getMessage() {
73 String message = getMessageText();
74 return String.format("%s%s", getCodeAsString(), message == null ? "" : ": " + message);
75 }
76
77 /**
78 * Get the message text without the error code prefix.
79 *
80 * @return the message text or {@code null}
81 */
82 @Nullable
83 public String getMessageText() {
84 return super.getMessage();
85 }
86
87 /**
88 * Get the error code value.
89 *
90 * @return the error code value
91 */
92 public int getCode() {
93 return code;
94 }
95
96 /**
97 * Get the error code family.
98 *
99 * @return the error code family
100 */
101 public abstract String getCodePrefix();
102
103 /**
104 * Get a combination of the error code family and value.
105 *
106 * @return the full error code.
107 */
108 protected String getCodeAsString() {
109 return String.format("%s%04d", getCodePrefix(), getCode());
110 }
111 }