Build, Test, and Push CFDM Docker Image / test (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / build-and-push (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / create-release (push) Has been cancelled
Build, Test, and Push CFDM Docker Image / update-wiki (push) Has been cancelled
69 lines
1.7 KiB
TypeScript
69 lines
1.7 KiB
TypeScript
import { NotFoundError, ConflictError } from "@cfdm/db";
|
|
import { ValidationError } from "@cfdm/shared";
|
|
|
|
export type ErrorCode =
|
|
| "NOT_FOUND"
|
|
| "VALIDATION_ERROR"
|
|
| "UNAUTHORIZED"
|
|
| "FORBIDDEN"
|
|
| "CONFLICT"
|
|
| "CLOUDFLARE_ERROR"
|
|
| "INTERNAL_ERROR";
|
|
|
|
export class AppError extends Error {
|
|
constructor(
|
|
public readonly code: ErrorCode,
|
|
message: string,
|
|
public readonly statusCode: number,
|
|
) {
|
|
super(message);
|
|
this.name = "AppError";
|
|
}
|
|
|
|
static notFound(message: string) {
|
|
return new AppError("NOT_FOUND", message, 404);
|
|
}
|
|
|
|
static validation(message: string) {
|
|
return new AppError("VALIDATION_ERROR", message, 400);
|
|
}
|
|
|
|
static unauthorized() {
|
|
return new AppError("UNAUTHORIZED", "unauthorized", 401);
|
|
}
|
|
|
|
static forbidden() {
|
|
return new AppError("FORBIDDEN", "forbidden", 403);
|
|
}
|
|
|
|
static conflict(message: string) {
|
|
return new AppError("CONFLICT", message, 409);
|
|
}
|
|
|
|
static cloudflare(message: string) {
|
|
return new AppError("CLOUDFLARE_ERROR", message, 502);
|
|
}
|
|
|
|
static internal(message: string) {
|
|
return new AppError("INTERNAL_ERROR", message, 500);
|
|
}
|
|
}
|
|
|
|
export function toAppError(err: unknown): AppError {
|
|
if (err instanceof AppError) return err;
|
|
if (err instanceof NotFoundError) return AppError.notFound(err.message);
|
|
if (err instanceof ConflictError) return AppError.conflict(err.message);
|
|
if (err instanceof ValidationError) return AppError.validation(err.message);
|
|
if (err instanceof Error) return AppError.internal(err.message);
|
|
return AppError.internal(String(err));
|
|
}
|
|
|
|
export function errorBody(err: AppError) {
|
|
return {
|
|
error: {
|
|
code: err.code,
|
|
message: err.message,
|
|
},
|
|
};
|
|
}
|