Skip to content

Commit

Permalink
refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
mapeveri committed Jan 28, 2024
1 parent bd9d563 commit 094dbb6
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import NotFoundException from '@src/shared/domain/exceptions/notFoundException';

export default class UserDoesNotExistsException extends NotFoundException {
constructor(userId: string) {
super(`User ${userId} doesn not exists`, 'user_does_not_exists');
super(`User ${userId} does not exists`, 'user_does_not_exists');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default class RefreshTokenPostController {
async run(@Body() payload: RefreshTokenPostDto): Promise<RefreshTokenPostResponseDto> {
const decodedRefreshToken = this.jwtService.verify(payload.refreshToken);
if (decodedRefreshToken.revoked) {
throw new HttpException('Token revocado', HttpStatus.FORBIDDEN);
throw new HttpException('Token revoked', HttpStatus.FORBIDDEN);
}

const user = await this.queryBus.ask(new FindUserQuery(decodedRefreshToken.id));
Expand Down
2 changes: 1 addition & 1 deletion src/shared/domain/exceptions/unauthorizedException.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import DomainException from '@src/shared/domain/exceptions/domainException';

export default class UnauthorizedException extends DomainException {
constructor(public message: string, public code: string) {
constructor(public message: string = 'User unauthorized', public code: string = 'user_unauthorized') {
super(message, code);
}
}
41 changes: 16 additions & 25 deletions src/shared/infrastructure/api/filters/nestErrorFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,45 +10,36 @@ import { Inject } from '@src/shared/domain/injector/inject.decorator';

@Catch(Error)
export class NestErrorFilter implements ExceptionFilter {
private mappedExceptions = [
{ exceptionType: ConflictException, status: HttpStatus.CONFLICT },
{ exceptionType: NotFoundException, status: HttpStatus.NOT_FOUND },
{ exceptionType: UnauthorizedException, status: HttpStatus.UNAUTHORIZED },
{ exceptionType: DomainException, status: HttpStatus.BAD_REQUEST },
];

constructor(@Inject(LOGGER_INTERFACE) private readonly logger: LoggerInterface) {}

catch(exception: Error, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();

this.logger.error(`Exception: ${exception}`);

if (exception instanceof ConflictException) {
response.status(HttpStatus.CONFLICT).json(ApiExceptionSerializer.serialize(exception, HttpStatus.CONFLICT));
return;
}

if (exception instanceof NotFoundException) {
response.status(HttpStatus.NOT_FOUND).json(ApiExceptionSerializer.serialize(exception, HttpStatus.NOT_FOUND));
return;
}

if (exception instanceof UnauthorizedException) {
response
.status(HttpStatus.UNAUTHORIZED)
.json(ApiExceptionSerializer.serialize(exception, HttpStatus.UNAUTHORIZED));
return;
}
this.logger.error(`${exception.stack}`);

if (exception instanceof DomainException) {
response
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json(ApiExceptionSerializer.serialize(exception, HttpStatus.INTERNAL_SERVER_ERROR));
const matchedException = this.mappedExceptions.find((item) => exception instanceof item.exceptionType);
if (matchedException) {
const status = matchedException.status;
response.status(status).json(ApiExceptionSerializer.serialize(exception as DomainException, status));
return;
}

if (exception instanceof HttpException) {
response.status(exception.getStatus()).json(exception.getResponse());
const status = exception.getStatus();
response.status(status).json({ statusCode: status, message: exception.message });
return;
}

response.status(500).json({
statusCode: 500,
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
message: 'Internal Server Error',
code: 'generic_error',
});
Expand Down
3 changes: 2 additions & 1 deletion src/shared/infrastructure/api/guards/nestJwtAuthGuard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { ConfigService } from '@nestjs/config';
import UnauthorizedException from '@src/shared/domain/exceptions/unauthorizedException';

@Injectable()
export class NestJwtAuthGuard implements CanActivate {
Expand Down

0 comments on commit 094dbb6

Please sign in to comment.