parent
9e5e4ae241
commit
3869e64ded
@ -0,0 +1,34 @@ |
|||||||
|
import { |
||||||
|
ArgumentsHost, |
||||||
|
Catch, |
||||||
|
ExceptionFilter, |
||||||
|
HttpException, |
||||||
|
} from "@nestjs/common"; |
||||||
|
import { Response, Request } from "express"; |
||||||
|
|
||||||
|
@Catch(HttpException) |
||||||
|
export class HttpExceptionFilter implements ExceptionFilter { |
||||||
|
catch(exception: HttpException, host: ArgumentsHost) { |
||||||
|
const ctx = host.switchToHttp(); |
||||||
|
const response = ctx.getResponse<Response>(); |
||||||
|
const request = ctx.getRequest<Request>(); |
||||||
|
const status = exception.getStatus(); |
||||||
|
const error = exception.getResponse() as |
||||||
|
| string |
||||||
|
| { error: string; statusCode: number; message: string | string[] }; |
||||||
|
|
||||||
|
if (typeof error === "string") { |
||||||
|
response.status(status).json({ |
||||||
|
timestamp: new Date().toISOString(), |
||||||
|
path: request.url, |
||||||
|
error, |
||||||
|
}); |
||||||
|
} else { |
||||||
|
response.status(status).json({ |
||||||
|
timestamp: new Date().toISOString(), |
||||||
|
path: request.url, |
||||||
|
...error, |
||||||
|
}); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
@ -1,9 +1,11 @@ |
|||||||
import { NestFactory } from "@nestjs/core"; |
import { NestFactory } from "@nestjs/core"; |
||||||
import { AppModule } from "./app.module"; |
import { AppModule } from "./app.module"; |
||||||
|
import { HttpExceptionFilter } from "./http-exception.filter"; |
||||||
|
|
||||||
async function bootstrap() { |
async function bootstrap() { |
||||||
const app = await NestFactory.create(AppModule); |
const app = await NestFactory.create(AppModule); |
||||||
app.enableCors(); |
app.enableCors(); |
||||||
|
app.useGlobalFilters(new HttpExceptionFilter()); |
||||||
await app.listen(process.env.PORT ?? 8000); |
await app.listen(process.env.PORT ?? 8000); |
||||||
} |
} |
||||||
bootstrap(); |
bootstrap(); |
||||||
|
Loading…
Reference in new issue