first commit
This commit is contained in:
1
libs/api/shared/presenters/src/index.ts
Normal file
1
libs/api/shared/presenters/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './lib/filters/domain-error.filter';
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { GqlContextType } from '@nestjs/graphql';
|
||||
import { DomainError, DomainErrorCode } from '@task-stream/api/shared/domain';
|
||||
import { Response } from 'express';
|
||||
import { GraphQLError } from 'graphql';
|
||||
|
||||
const HTTP_STATUS: Record<DomainErrorCode, HttpStatus> = {
|
||||
NOT_FOUND: HttpStatus.NOT_FOUND,
|
||||
FORBIDDEN: HttpStatus.FORBIDDEN,
|
||||
VALIDATION: HttpStatus.BAD_REQUEST,
|
||||
CONFLICT: HttpStatus.CONFLICT,
|
||||
BUSINESS_RULE: HttpStatus.UNPROCESSABLE_ENTITY,
|
||||
};
|
||||
|
||||
/** Translates domain errors into GraphQL errors (extensions.code) or HTTP responses. */
|
||||
@Catch(DomainError)
|
||||
export class DomainErrorFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(DomainErrorFilter.name);
|
||||
|
||||
catch(error: DomainError, host: ArgumentsHost): unknown {
|
||||
this.logger.debug(`${error.name}: ${error.message}`);
|
||||
if (host.getType<GqlContextType>() === 'graphql') {
|
||||
return new GraphQLError(error.message, {
|
||||
extensions: { code: error.code },
|
||||
});
|
||||
}
|
||||
const response = host.switchToHttp().getResponse<Response>();
|
||||
return response.status(HTTP_STATUS[error.code]).json({
|
||||
statusCode: HTTP_STATUS[error.code],
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user