-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy patherrors.ts
More file actions
82 lines (69 loc) · 1.99 KB
/
Copy patherrors.ts
File metadata and controls
82 lines (69 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { ZodError } from "zod";
export type ErrorCode =
| "VALIDATION_ERROR"
| "UNAUTHORIZED"
| "FORBIDDEN"
| "NOT_FOUND"
| "CONFLICT"
| "INTERNAL_ERROR";
export type ErrorDetails = Record<string, unknown>;
export class AppError extends Error {
readonly code: ErrorCode;
readonly statusCode: number;
readonly details?: ErrorDetails;
constructor(
code: ErrorCode,
message: string,
statusCode: number,
details?: ErrorDetails,
) {
super(message);
this.name = "AppError";
this.code = code;
this.statusCode = statusCode;
this.details = details;
}
static validation(
message = "Dados inválidos",
details?: ErrorDetails,
): AppError {
return new AppError("VALIDATION_ERROR", message, 400, details);
}
static unauthorized(message = "Não autenticado."): AppError {
return new AppError("UNAUTHORIZED", message, 401);
}
static forbidden(message = "Acesso negado."): AppError {
return new AppError("FORBIDDEN", message, 403);
}
static notFound(message = "Recurso não encontrado."): AppError {
return new AppError("NOT_FOUND", message, 404);
}
static conflict(message: string, details?: ErrorDetails): AppError {
return new AppError("CONFLICT", message, 409, details);
}
static internal(
message = "Erro interno.",
details?: ErrorDetails,
): AppError {
return new AppError("INTERNAL_ERROR", message, 500, details);
}
static fromZodError(
error: ZodError,
message = "Dados inválidos",
): AppError {
return AppError.validation(message, error.flatten().fieldErrors);
}
toJSON(): { code: ErrorCode; message: string; details?: ErrorDetails } {
const body: { code: ErrorCode; message: string; details?: ErrorDetails } = {
code: this.code,
message: this.message,
};
if (this.details !== undefined) {
body.details = this.details;
}
return body;
}
}
export function isAppError(error: unknown): error is AppError {
return error instanceof AppError;
}