2024-08-26 04:30:09 +00:00
|
|
|
import { StatusCodes } from "http-status-codes";
|
|
|
|
|
import { ErrorCode } from "./errorCodes";
|
2024-09-10 06:16:41 +00:00
|
|
|
import { ZodError } from "zod";
|
2024-08-26 04:30:09 +00:00
|
|
|
|
2024-09-10 06:16:41 +00:00
|
|
|
export interface ServiceError {
|
2024-08-26 04:30:09 +00:00
|
|
|
statusCode: StatusCodes;
|
|
|
|
|
errorCode: ErrorCode;
|
|
|
|
|
message: string;
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-10 06:16:41 +00:00
|
|
|
export const serviceErrorResponse = ({ statusCode, errorCode, message }: ServiceError) => {
|
2024-08-26 04:30:09 +00:00
|
|
|
return Response.json({
|
|
|
|
|
statusCode,
|
|
|
|
|
errorCode,
|
|
|
|
|
message,
|
|
|
|
|
}, {
|
|
|
|
|
status: statusCode,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-10 06:16:41 +00:00
|
|
|
export const missingQueryParam = (name: string): ServiceError => {
|
|
|
|
|
return {
|
2024-08-26 04:30:09 +00:00
|
|
|
statusCode: StatusCodes.BAD_REQUEST,
|
|
|
|
|
errorCode: ErrorCode.MISSING_REQUIRED_QUERY_PARAMETER,
|
|
|
|
|
message: `Missing required query parameter: ${name}`,
|
2024-09-10 06:16:41 +00:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const schemaValidationError = (error: ZodError): ServiceError => {
|
|
|
|
|
return {
|
|
|
|
|
statusCode: StatusCodes.BAD_REQUEST,
|
|
|
|
|
errorCode: ErrorCode.INVALID_REQUEST_BODY,
|
|
|
|
|
message: `Schema validation failed with: ${error.message}`,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const invalidZoektResponse = async (zoektResponse: Response): Promise<ServiceError> => {
|
|
|
|
|
const zoektMessage = await (async () => {
|
|
|
|
|
try {
|
|
|
|
|
const zoektResponseBody = await zoektResponse.json();
|
|
|
|
|
if (zoektResponseBody.Error) {
|
|
|
|
|
return zoektResponseBody.Error;
|
|
|
|
|
}
|
|
|
|
|
} catch (_e) {
|
|
|
|
|
return "Unknown error";
|
|
|
|
|
}
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
|
|
|
|
|
errorCode: ErrorCode.INVALID_REQUEST_BODY,
|
|
|
|
|
message: `Zoekt request failed with status code ${zoektResponse.status} and message: "${zoektMessage}"`,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const fileNotFound = async (fileName: string, repository: string): Promise<ServiceError> => {
|
|
|
|
|
return {
|
|
|
|
|
statusCode: StatusCodes.NOT_FOUND,
|
|
|
|
|
errorCode: ErrorCode.FILE_NOT_FOUND,
|
|
|
|
|
message: `File "${fileName}" not found in repository "${repository}"`,
|
|
|
|
|
};
|
2024-09-10 19:24:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const unexpectedError = (message: string): ServiceError => {
|
|
|
|
|
return {
|
|
|
|
|
statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
|
|
|
|
|
errorCode: ErrorCode.UNEXPECTED_ERROR,
|
|
|
|
|
message: `Unexpected error: ${message}`,
|
|
|
|
|
};
|
2024-08-26 04:30:09 +00:00
|
|
|
}
|