Skip to content

Commit

Permalink
feat(error handler): catch more cases
Browse files Browse the repository at this point in the history
  • Loading branch information
phucvinh57 committed Aug 22, 2023
1 parent ab84294 commit c746a39
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
15 changes: 13 additions & 2 deletions src/configs/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import { TRY_LATER } from '@constants';
import { NOT_FOUND_GENERIC, TRY_LATER } from '@constants';
import { FastifyError, FastifyReply, FastifyRequest } from 'fastify';

export function customErrorHandler(err: FastifyError, _req: FastifyRequest, res: FastifyReply) {
if (err.statusCode === undefined || err.statusCode >= 500) {
if (err.statusCode === undefined) {
if (err.name === 'NotFoundError' || err.code === 'P2025') {
err.statusCode = 400;
err.message = NOT_FOUND_GENERIC;
return res.send(err);
}
err.statusCode = 500;
}

// Intentionally thrown errors
if (err.statusCode >= 500) {
err.message = TRY_LATER;
return res.send(err);
}

if (!err.validation || err.validation.length === 0) {
return res.send(err);
}
Expand Down
1 change: 1 addition & 0 deletions src/constants/errorMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export const DUPLICATED_EMAIL = 'Email already exists !';
export const LOGIN_FAIL = 'Incorrect login information !';
export const MUST_LOGIN_FIRST = 'Login first !';
export const INVALID_TOKEN = 'Invalid token !';
export const NOT_FOUND_GENERIC = 'Not found !';
2 changes: 2 additions & 0 deletions src/handlers/auth.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { User } from '@prisma/client';
import { AuthInputDto } from '@dtos/in';
import { AuthResultDto } from '@dtos/out';
import { Handler } from '@interfaces';
import { logger } from '@utils';

const login: Handler<AuthResultDto, { Body: AuthInputDto }> = async (req, res) => {
const user = await prisma.user.findUnique({
Expand Down Expand Up @@ -42,6 +43,7 @@ const signup: Handler<AuthResultDto, { Body: AuthInputDto }> = async (req, res)
}
});
} catch (err) {
logger.info(err);
return res.badRequest(DUPLICATED_EMAIL);
}

Expand Down
2 changes: 1 addition & 1 deletion src/utils/createRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function createRoutes(swaggerTag: HandlerTag, routesOptions: RouteOptions
tags: [swaggerTag]
},
/**
* True by default. See https://www.fastify.io/docs/latest/Reference/Server/#exposeHeadRoutes
* True by default. See https://www.fastify.dev/docs/latest/Reference/Server/#exposeHeadRoutes
* About HEAD http method: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
*/
exposeHeadRoute: false
Expand Down

0 comments on commit c746a39

Please sign in to comment.