'Genericise' errors ready for +error.svelte upgrade to handle known errors
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { OwlBoardClient, ValidationError, ApiError } from '@owlboard/owlboard-ts';
|
||||
import { browser, dev } from '$app/environment';
|
||||
import { error } from '@sveltejs/kit';
|
||||
|
||||
// Import the runes containing the API Key config Here...
|
||||
|
||||
@@ -18,6 +19,46 @@ export const OwlClient = new OwlBoardClient(
|
||||
// API Key Here when ready!!!
|
||||
);
|
||||
|
||||
export function ThrowApiError(e: any): void {}
|
||||
export function ThrowApiError(e: unknown): never {
|
||||
// Handle Request failure
|
||||
if (e instanceof TypeError && e.message === 'Failed to fetch') {
|
||||
throw error(503, {
|
||||
message: 'Unable to connect to the OwlBoard server',
|
||||
name: 'NETWORK_ERROR',
|
||||
code: 'NETWORK_UNREACHABLE'
|
||||
});
|
||||
}
|
||||
|
||||
// Map ApiError 'code' values
|
||||
if (e instanceof ApiError) {
|
||||
let status = 500;
|
||||
if (e.code === 'AUTH') {
|
||||
status = 401;
|
||||
} else if (e.code === 'NOT_FOUND') {
|
||||
status = 404;
|
||||
} else if (e.code === 'RATE_LIMIT') {
|
||||
status = 421;
|
||||
} else if (e.code === 'NETWORK_DISCONNECTED') {
|
||||
status = 503;
|
||||
} else if (e.code === 'VALIDATION') {
|
||||
status = 400;
|
||||
}
|
||||
|
||||
throw error(status, {
|
||||
message: e.message || 'An operational error has occurred',
|
||||
name: e.name || 'API_ERROR',
|
||||
code: e.code || 'UNKNOWN_API_ERROR'
|
||||
});
|
||||
}
|
||||
|
||||
// Fallback for other error kind
|
||||
const genericMessage = e instanceof Error ? e.message : 'An unexpected error occurred.';
|
||||
throw error(500, {
|
||||
message: genericMessage,
|
||||
name: 'CRITICAL_ERROR',
|
||||
code: 'INTERNAL_ERROR',
|
||||
msg: 'UNHANDLED_EXCEPTION'
|
||||
});
|
||||
}
|
||||
|
||||
export { ValidationError, ApiError };
|
||||
|
||||
Reference in New Issue
Block a user