All files / src apiError.ts

100% Statements 5/5
100% Branches 6/6
100% Functions 1/1
100% Lines 5/5

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                  9x 9x 8x 7x         2x    
import type { components } from './api'
 
type ErrorResponse = components['schemas']['ErrorResponse']
 
/**
 * Returns the server's ErrorResponse `message` from a failed response body,
 * falling back to `fallback` (or a generic message) when the body carries none.
 */
export async function errorMessage(res: Response, fallback?: string): Promise<string> {
	try {
		const data = (await res.json()) as Partial<ErrorResponse>
		if (typeof data?.message === 'string' && data.message.trim() !== '') {
			return data.message
		}
	} catch {
		// fall through
	}
	return fallback ?? `An error occured. (HTTP ${res.status})`
}