import { Catch, ExceptionFilter, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';

@Catch()
export class ErrorHandler implements ExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        let status = HttpStatus.INTERNAL_SERVER_ERROR;
        let message: any = exception.message || "Internal Server Error";
        if (!Array.isArray(message)) {
            message = [message]
        }
        if (exception instanceof HttpException) {
            status = exception.getStatus();
            message = exception.getResponse()['message'] || exception.message;
            if (!Array.isArray(message)) {
                message = [message]
            }
        }
        response.status(status).json({
            statusCode: status,
            message: message[0]
        });
    }
}

