Loader
Khi sử dụng loader
trong remix, trong trường hợp xảy ra lỗi nên sử dụng các class error trong app/domain/response/error.ts
export class NotFoundError extends ErrorResponse {
constructor(message?: string) {
super(message || 'Page not found', 404);
}
}
export class BadRequestError extends ErrorResponse {
constructor(message?: string) {
super(message || 'Bad request', 400);
}
}
export class UnauthorizedError extends ErrorResponse {
constructor(message?: string) {
super(message || 'Unauthorized', 401);
}
}
export class ForbiddenError extends ErrorResponse {
constructor(message?: string) {
super(message || 'Forbidden', 403);
}
}
export class InternalServerError extends ErrorResponse {
constructor(message?: string) {
super(message || 'Internal server error', 500);
}
}
Ví dụ
import { json, type LoaderFunctionArgs } from '@remix-run/node';
import { isValidObjectId } from 'mongoose';
import { getTodoByIdUseCase } from '~/application/use-cases/todo/get-by-id.use-case';
import { NotFoundError } from '~/domain/response/error';
import { todoRepository } from '~/infrastructure/models/todo';
export const todoByIdLoader = async ({ params }: LoaderFunctionArgs) => {
const id = params.id;
if (!id) throw new NotFoundError('Todo not found');
if (id === 'new') return null;
if (!isValidObjectId(id)) throw new NotFoundError('Todo not found');
const todo = await getTodoByIdUseCase(todoRepository, id);
return json(todo);
};