Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 2x 2x 2x 2x 2x 2x 13x 2x 17x 1x 2x 2x 9x 9x 8x 8x 1x 1x | import { ApiError, HTTP_STATUS_CODES } from "estuary-rpc";
export const DEFAULT_BAD_REQUEST = "Bad Request";
export const DEFAULT_INTERNAL_SERVER_ERROR = "Internal Server Error";
export const DEFAULT_NOT_FOUND = "Page Not Found";
export const DEFAULT_UNAUTHORIZED = "Unauthorized";
/**
* Errors sent from client to server should be of this type, encoded in JSON
* @group Server
*/
export type ErrorResponse = {
status: "error";
message: string;
};
/**
* @param message Error Message
* @returns Common JSON representation used for an error for transmission to the client
* @group Server
*/
export function errorResponse(message: string) {
return JSON.stringify({
status: "error",
message,
});
}
/**
*
* @param respond Method allowing for a response to the client, obfuscating the underlying transport
* @returns An object with two methods to be used for returning common errors to the client
* @group Server
*/
export function createErrorHandlers(
respond: (status: number, message?: string) => void
) {
return {
badRequest: (message?: string) =>
respond(
HTTP_STATUS_CODES.BAD_REQUEST,
errorResponse(message || DEFAULT_BAD_REQUEST)
),
internalServerError: (message?: string) =>
respond(
HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,
errorResponse(message ?? DEFAULT_INTERNAL_SERVER_ERROR)
),
};
}
export const DEFAULT_TOO_LARGE = "Request Too Large";
/**
* Answers an error thrown while handling a call: an {@link ApiError} with its status and message, anything else
* mapped by `mapError`, else logged and answered with a bare internal server error.
* @group Server
*/
export function answerError(
respond: (status: number, message?: string) => void,
error: unknown,
where: string,
mapError?: (error: unknown) => ApiError | undefined
) {
const apiError =
ApiError.is(error) ? error : mapError?.(error) ?? undefined;
if (apiError) {
respond(apiError.status, errorResponse(apiError.message));
return;
}
console.error(`${where}:`, error);
respond(
HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,
errorResponse(DEFAULT_INTERNAL_SERVER_ERROR)
);
}
|