UNPKG

2.3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const shared_utils_1 = require("../utils/shared.utils");
4/**
5 * Defines the base Nest HTTP exception, which is handled by the default
6 * Exceptions Handler.
7 *
8 * @see [Base Exceptions](https://docs.nestjs.com/exception-filters#base-exceptions)
9 *
10 * @publicApi
11 */
12class HttpException extends Error {
13 /**
14 * Instantiate a plain HTTP Exception.
15 *
16 * @example
17 * `throw new HttpException()`
18 *
19 * @usageNotes
20 * The constructor arguments define the HTTP response.
21 * - The `response` argument (required) defines the JSON response body.
22 * - The `status` argument (required) defines the HTTP Status Code.
23 *
24 * By default, the JSON response body contains two properties:
25 * - `statusCode`: defaults to the Http Status Code provided in the `error` argument
26 * - `message`: a short description of the HTTP error by default; override this
27 * by supplying a string in the `response` parameter.
28 *
29 * To override the entire JSON response body, pass an object. Nest will serialize
30 * the object and return it as the JSON response body.
31 *
32 * The `status` argument is required, and should be a valid HTTP status code.
33 * Best practice is to use the `HttpStatus` enum imported from `nestjs/common`.
34 *
35 * @param response string or object describing the error condition.
36 * @param status HTTP response status code
37 */
38 constructor(response, status) {
39 super();
40 this.response = response;
41 this.status = status;
42 this.message = response;
43 }
44 getResponse() {
45 return this.response;
46 }
47 getStatus() {
48 return this.status;
49 }
50 toString() {
51 const message = this.getErrorString(this.message);
52 return `Error: ${message}`;
53 }
54 getErrorString(target) {
55 return shared_utils_1.isString(target) ? target : JSON.stringify(target);
56 }
57 static createBody(message, error, statusCode) {
58 if (!message) {
59 return { statusCode, error };
60 }
61 return shared_utils_1.isObject(message) && !Array.isArray(message)
62 ? message
63 : { statusCode, error, message };
64 }
65}
66exports.HttpException = HttpException;