Files
nest/packages/common/exceptions/http.exception.ts
2020-03-02 14:39:49 +01:00

81 lines
2.3 KiB
TypeScript

import { isObject, isString } from '../utils/shared.utils';
/**
* Defines the base Nest HTTP exception, which is handled by the default
* Exceptions Handler.
*
* @see [Base Exceptions](https://docs.nestjs.com/exception-filters#base-exceptions)
*
* @publicApi
*/
export class HttpException extends Error {
/**
* Instantiate a plain HTTP Exception.
*
* @example
* `throw new HttpException()`
*
* @usageNotes
* The constructor arguments define the HTTP response.
* - The `response` argument (required) defines the JSON response body.
* - The `status` argument (required) defines the HTTP Status Code.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: defaults to the Http Status Code provided in the `error` argument
* - `message`: a short description of the HTTP error by default; override this
* by supplying a string in the `response` parameter.
*
* To override the entire JSON response body, pass an object. Nest will serialize
* the object and return it as the JSON response body.
*
* The `status` argument is required, and should be a valid HTTP status code.
* Best practice is to use the `HttpStatus` enum imported from `nestjs/common`.
*
* @param response string or object describing the error condition.
* @param status HTTP response status code
*/
constructor(
private readonly response: string | Record<string, any>,
private readonly status: number,
) {
super();
this.initMessage();
}
public initMessage() {
if (isString(this.response)) {
this.message = this.response;
} else if (
isObject(this.response) &&
isString((this.response as Record<string, any>).message)
) {
this.message = (this.response as Record<string, any>).message;
} else if (this.constructor) {
this.message = this.constructor.name
.match(/[A-Z][a-z]+|[0-9]+/g)
.join(' ');
}
}
public getResponse(): string | object {
return this.response;
}
public getStatus(): number {
return this.status;
}
public static createBody(
message: object | string,
error?: string,
statusCode?: number,
) {
if (!message) {
return { statusCode, error };
}
return isObject(message) && !Array.isArray(message)
? message
: { statusCode, error, message };
}
}