diff --git a/docs/overview/error-handling.md b/docs/overview/error-handling.md index 0701168b..4fc4ec29 100644 --- a/docs/overview/error-handling.md +++ b/docs/overview/error-handling.md @@ -4,7 +4,7 @@ sidebar_position: 14 # Error Handling -When it comes to error handling in Node.js TypeScript APIs, there are several best practices and approaches you can follow. ExpressoTS providers a simple and easy way to handle errors. +When it comes to error handling in Node.js TypeScript APIs, there are several best practices and approaches you can follow. ExpressoTS provides a simple and easy way to handle errors. - We use HTTP status codes appropriately: HTTP **[status codes](./status-code.md)** are used to indicate the status of a response. It is important to use them appropriately in your API to indicate the success or failure of an operation. @@ -22,7 +22,7 @@ When it comes to error handling in Node.js TypeScript APIs, there are several be We developed a standardized error reporting class called `Report` that provides a centralized location for throwing and handling errors, which can simplify error handling throughout the application. -The errorHandler function provides a centralized location for handling errors that occur during request processing. By defining a standard error response format, it helps to ensure consistency in error messages that are returned to clients. +By defining a standard error response format, it helps to ensure consistency in error messages that are returned to clients. This approach is best used in applications with a large codebase or complex business logic, where errors may occur frequently and need to be handled consistently across different parts of the application. @@ -32,42 +32,81 @@ Report class is a utility class to manage and throw application-specific errors. ```typescript class Report { - - /** - * Error method takes an instance of Error and throws it. - * @param error - An instance of Error or a string representing the error message. - * @param statusCode - The HTTP status code of the error. - * @param service - The service where the error occurred. - */ - public static Error(error: Error | string, statusCode?: number, service?: string): void { } + /** + * The Error method is responsible for generating a standardized error object, + * logging the error, and then throwing it for further handling. + * The error thrown is of the custom type AppError, which extends the built-in Error class. + * + * @param error - An instance of Error or a string that describes the error. + * @param statusCode - The HTTP status code associated with the error (default is 500). + * @param service - The service name associated with the error. If not specified, + * it defaults to the name of the calling function. + * + * @throws An object of the custom type AppError, which includes details about the error. + */ + public Error( + error: Error | string, + statusCode?: number, + service?: string, + ): AppError { } ``` -Once you report a known error through the `Report.Error()` method, the error will be handled by the `errorHandler()` middleware and will be returned to the client in the json parsed format. +Once you report a known error through the `Report.Error()` method, the error will be handled by the `defaultErrorHandler()` middleware and will be returned to the client in the json parsed format. ### Middleware This middleware function is used to handle errors that occur during request processing. ```typescript -function errorHandler(error: IAppError, req: Request, res: Response, next: NextFunction): void { - res.status(error.statusCode || StatusCode.InternalServerError).json({statusCode: error.statusCode, error: error.message}); +/** + * errorHandler is a custom Express error-handling middleware function. + * It logs the error, sets the status code, and sends a JSON response containing the status code and error message. + * @param error - An instance of IAppError containing error details. + * @param req - The Express request object. + * @param res - The Express response object. + * @param next - The Express next function for passing control to the next middleware function. + */ +function defaultErrorHandler( + error: Error, + req: Request, + res: Response, + next: NextFunction +): void { + if (error instanceof AppError) { + res + .status(error.statusCode) + .json({ statusCode: error.statusCode, error: error.message }); + } else { + res.status(StatusCode.InternalServerError).json({ + statusCode: StatusCode.InternalServerError, + error: "An unexpected error occurred.", + }); + } } -export default errorHandler; +export default defaultErrorHandler; ``` :::info -function `errorHandler()` is a custom Express error-handling middleware function. +function `defaultErrorHandler()` is a custom Express error-handling middleware function. It logs the error, sets the status code, and sends a JSON response containing the status code and error message. ::: ## Example of use ```typescript -Report.Error(error, StatusCode.BadRequest, "your-service"); -// Or -Report.Error("your-error", StatusCode.BadRequest, "your-service"); +class FooClass { + constructor(private report: Report) {} + + execute() { + try { + // do something + } catch (error: any) { + this.report.Error(error, StatusCode.BadRequest, "your-service"); + } + } +} ``` Use case example: @@ -75,49 +114,55 @@ Use case example: ```typescript @provide(CreateUserUseCase) class CreateUserUseCase { - constructor(private userRepository: UserRepository) {} - - execute(data: ICreateUserRequestDTO): ICreateUserResponseDTO | null { - try { - const { name, email } = data; - - const userAlreadyExists = await this.userRepository.findByEmail(email); - - if (userAlreadyExists) { - Report.Error("User already exists", StatusCode.BadRequest, "create-user-usecase"); - } - - const user: User | null = this.userRepository.create(new User(name, email)); - - let response: ICreateUserResponseDTO; - - if (user !== null) { - response = { - id: user.Id, - name: user.name, - email: user.email, - status: "success", - }; - return response; - } - - return null; - } catch (error: any) { - throw error; - } + constructor(private userRepository: UserRepository, private report: Report) {} + + execute(data: ICreateUserRequestDTO): ICreateUserResponseDTO | null { + try { + const { name, email } = data; + + const userAlreadyExists = await this.userRepository.findByEmail(email); + + if (userAlreadyExists) { + this.report.Error( + "User already exists", + StatusCode.BadRequest, + "create-user-usecase" + ); + } + + const user: User | null = this.userRepository.create( + new User(name, email) + ); + + let response: ICreateUserResponseDTO; + + if (user !== null) { + response = { + id: user.Id, + name: user.name, + email: user.email, + status: "success", + }; + return response; + } + + return null; + } catch (error: any) { + throw error; } + } } ``` ## Error components description -| Object | Description | -| --------------- | ----------------------------------------------------------------------- | -| Report.Error | Static method to report known errors. | -| IAppError | App Error interface that defines error object format. | -| StatusCode | Http responses code and message. | -| Error Message | Error message detail that the developer wants to log. | -| Error Service | To be used in the log system to indicate where the error was generated. | +| Object | Description | +| ------------- | ----------------------------------------------------------------------- | +| Report.Error | Method to report known errors. | +| AppError | App Error class that defines error object format. | +| StatusCode | Http responses code and message. | +| Error Message | Error message detail that the developer wants to log. | +| Error Service | To be used in the log system to indicate where the error was generated. | --- @@ -130,4 +175,4 @@ ExpressoTS is an MIT-licensed open source project. It's an independent project w - Subscribe to the Twitch channel: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** - Join our **[Discord](https://discord.com/invite/PyPJfGK)** - Contribute submitting **[issues and pull requests](https://github.com/expressots/expressots/issues/new/choose)** -- Share the project with your friends and colleagues \ No newline at end of file +- Share the project with your friends and colleagues diff --git a/docusaurus.config.js b/docusaurus.config.js index 6d49c5b4..24ca87ab 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -116,7 +116,7 @@ const config = { }, announcementBar: { id: "supportus", - content: "Current Version: v1.7.0", + content: "Current Version: v1.8.1", backgroundColor: "#111", textColor: "#19CE59", isCloseable: false, diff --git a/i18n/pt/docusaurus-plugin-content-docs/current/overview/error-handling.md b/i18n/pt/docusaurus-plugin-content-docs/current/overview/error-handling.md index 68707957..005916dc 100644 --- a/i18n/pt/docusaurus-plugin-content-docs/current/overview/error-handling.md +++ b/i18n/pt/docusaurus-plugin-content-docs/current/overview/error-handling.md @@ -18,56 +18,89 @@ Quando se trata de tratamento de erros nas APIs TypeScript do Node.js, existem v - Registramos erros: o registro de erros é importante para depuração e monitoramento. -## Nossa solução +## Nossa Abordagem -Desenvolvemos uma classe de relatório de erros padronizada chamada `Report` que fornece um local centralizado para lançamento e tratamento de erros, o que pode simplificar o tratamento de erros em todo o aplicativo. +Desenvolvemos uma classe de relatório de erro padronizada chamada Report que oferece um local centralizado para lançar e tratar erros, o que pode simplificar o tratamento de erros em toda a aplicação. -A função errorHandler fornece um local centralizado para manipulação de erros que ocorrem durante o processamento da solicitação. Ao definir um formato de resposta de erro padrão, ele ajuda a garantir a consistência nas mensagens de erro que são retornadas aos clientes. +Ao definir um formato de resposta de erro padrão, ajuda a garantir consistência nas mensagens de erro retornadas aos clientes. -Essa abordagem é melhor usada em aplicativos com uma grande base de código ou lógica de negócios complexa, onde os erros podem ocorrer com frequência e precisam ser tratados de forma consistente em diferentes partes do aplicativo. +Esta abordagem é melhor usada em aplicações com um grande código-base ou lógica de negócios complexa, onde erros podem ocorrer com frequência e precisam ser tratados de forma consistente em diferentes partes da aplicação. -### Report error +### Report Error -A classe de relatório é uma classe de utilitário para gerenciar e lançar erros específicos do aplicativo. +A classe Report é uma classe de utilitário para gerenciar e lançar erros específicos do aplicativo. ```typescript class Report { - - /** - * O método Error pega uma instância de Error e a lança. - * @param error - Uma instância de Error ou uma string que representa a mensagem de erro. - * @param statusCode - O código de status HTTP do erro. - * @param service - O serviço onde ocorreu o erro. - */ - public static Error(error: Error | string, statusCode?: number, service?: string): void { } + /** + * O método Error pega uma instância de Error e a lança. + * @param error - Uma instância de Error ou uma string que representa a mensagem de erro. + * @param statusCode - O código de status HTTP do erro. + * @param service - O serviço onde ocorreu o erro. + */ + public static Error( + error: Error | string, + statusCode?: number, + service?: string + ): void {} } ``` -Depois de relatar um erro conhecido por meio do método `Report.Error()`, o erro será tratado pelo middleware `errorHandler()` e será retornado ao cliente no formato json analisado. +Depois de relatar um erro conhecido por meio do método `Report.Error()`, o erro será tratado pelo middleware `defaultErrorHandler()` e será retornado ao cliente no formato json analisado. ### Middleware Essa função de middleware é usada para manipular erros que ocorrem durante o processamento da solicitação. ```typescript -function errorHandler(error: IAppError, req: Request, res: Response, next: NextFunction): void { - res.status(error.statusCode || StatusCode.InternalServerError).json({statusCode: error.statusCode, error: error.message}); +/** + * errorHandler é uma função de middleware de tratamento de erros personalizada do Express. + * Ela registra o erro, define o código de status e envia uma resposta JSON contendo o código de status e a mensagem de erro. + * @param error - Uma instância de AppError contendo detalhes do erro. + * @param req - O objeto de solicitação do Express. + * @param res - O objeto de resposta do Express. + * @param next - A função next do Express para passar o controle para a próxima função de middleware. + */ +function defaultErrorHandler( + error: Error, + req: Request, + res: Response, + next: NextFunction +): void { + if (error instanceof AppError) { + res + .status(error.statusCode) + .json({ statusCode: error.statusCode, error: error.message }); + } else { + res.status(StatusCode.InternalServerError).json({ + statusCode: StatusCode.InternalServerError, + error: "Ocorreu um erro inesperado.", + }); + } } -export default errorHandler; +export default defaultErrorHandler; ``` :::info -A função `errorHandler()` é uma função de middleware de tratamento de erros Express personalizada. -Ele registra o erro, define o código de status e envia uma resposta JSON contendo o código de status e a mensagem de erro. +A função `defaultErrorHandler()` é uma função de middleware de tratamento de erros personalizada do Express. +Ela registra o erro, define o código de status e envia uma resposta JSON contendo o código de status e a mensagem de erro. ::: ## Exemplo de uso ```typescript -Report.Error(error, StatusCode.BadRequest, "your-service"); -// Ou -Report.Error("your-error", StatusCode.BadRequest, "your-service"); +class FooClass { + constructor(private report: Report) {} + + execute() { + try { + // fazer algo + } catch (error: any) { + this.report.Error(error, StatusCode.BadRequest, "seu-servico"); + } + } +} ``` Use case example: @@ -75,49 +108,55 @@ Use case example: ```typescript @provide(CreateUserUseCase) class CreateUserUseCase { - constructor(private userRepository: UserRepository) {} - - execute(data: ICreateUserRequestDTO): ICreateUserResponseDTO | null { - try { - const { name, email } = data; - - const userAlreadyExists = await this.userRepository.findByEmail(email); - - if (userAlreadyExists) { - Report.Error("User already exists", StatusCode.BadRequest, "create-user-usecase"); - } - - const user: User | null = this.userRepository.create(new User(name, email)); - - let response: ICreateUserResponseDTO; - - if (user !== null) { - response = { - id: user.Id, - name: user.name, - email: user.email, - status: "success", - }; - return response; - } - - return null; - } catch (error: any) { - throw error; - } + constructor(private userRepository: UserRepository, private report: Report) {} + + execute(data: ICreateUserRequestDTO): ICreateUserResponseDTO | null { + try { + const { name, email } = data; + + const userAlreadyExists = await this.userRepository.findByEmail(email); + + if (userAlreadyExists) { + this.report.Error( + "User already exists", + StatusCode.BadRequest, + "create-user-usecase" + ); + } + + const user: User | null = this.userRepository.create( + new User(name, email) + ); + + let response: ICreateUserResponseDTO; + + if (user !== null) { + response = { + id: user.Id, + name: user.name, + email: user.email, + status: "success", + }; + return response; + } + + return null; + } catch (error: any) { + throw error; } + } } ``` ## Descrição dos componentes de tratamento de erro -| Objeto | Descrição | -| --------------- | -------------------------------------------------------------- | -| Report.Error | Método estático para reportar erros conhecidos. | -| IAppError | Interface de erro do aplicativo que define o formato do objeto de erro. | -| StatusCode | Código de status HTTP. | -| Error Message | Detalhes da mensagem de erro que o desenvolvedor deseja registrar. | -| Error Service | Serviço que originou o erro, a ser utilizado no sistema de log. | +| Objeto | Descrição | +| ------------- | -------------------------------------------------------------------- | +| Report.Error | Método estático para reportar erros conhecidos. | +| AppError | Classe de erro do aplicativo que define o formato do objeto de erro. | +| StatusCode | Código de status HTTP. | +| Error Message | Detalhes da mensagem de erro que o desenvolvedor deseja registrar. | +| Error Service | Serviço que originou o erro, a ser utilizado no sistema de log. | --- @@ -130,4 +169,4 @@ ExpressoTS é um projeto de código aberto licenciado sob o MIT. É um projeto i - Subscreva no nosso canal na Twitch: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** - Entre no nosso **[Discord](https://discord.com/invite/PyPJfGK)** - Contribua submetendo **[issues e pull requests](https://github.com/expressots/expressots/issues/new/choose)** -- Compartilhe o projeto com seus amigos e colegas \ No newline at end of file +- Compartilhe o projeto com seus amigos e colegas