• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package std.core;
17
18/**
19 * Strores information about stacktrace and cause in case of an exception.
20 * Serves as a base class for all exception classes.
21 */
22export class Exception {
23  private stackLines: String[];
24  message: String;
25  private cause: Object;
26  private provisionStackTrace(): void {
27    this.stackLines = stackTraceLines();
28  }
29
30  /**
31   * Constructs a new empty exception instance
32   */
33  constructor () {
34    this.message = "";
35    this.cause = this;
36    this.provisionStackTrace();
37  }
38
39  /**
40   * Constructs a new exception instance with provided message
41   *
42   * @param msg message of the exception
43   */
44  constructor(msg: String) {
45    this.message = msg;
46    this.cause = this;
47    this.provisionStackTrace()
48  }
49
50  /**
51   * Constructs a new exception instance with provided message and cause
52   *
53   * @param msg message of the exception
54   *
55   * @param cause cause of the exception
56   */
57  constructor(msg: String, cause: Object) {
58    this.message = msg;
59    this.cause = cause;
60    this.provisionStackTrace();
61  }
62
63  /**
64    * Converts this excepiton to a string
65    * Result includes exception message and the stacktrace
66    *
67    * @returns result of the conversion
68    */
69  override toString(): String {
70    let s: String = "";
71
72    if (this.message != "") {
73      s += this.message + "\n";
74    }
75
76    for (let i: int = (this.stackLines.length > 2 ? 2 : 0); i < this.stackLines.length; i++) {
77      s += this.stackLines[i];
78      if (i != this.stackLines.length-1) {
79        s += "\n";
80      }
81    }
82
83    return s;
84  }
85
86  /**
87   * Returns the cause of this excepiton
88   *
89   * @returns the cause
90   */
91  public getCause(): Object | null {
92    if (this.cause == this) {
93      return null;
94    } else {
95      return this.cause;
96    }
97  }
98}
99