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