Errors
Every failure of the encoder and the decoder is a PlaceholderError. It is an ordinary Error subclass with a machine-readable code, so you can tell a bad hash from a bad image without parsing messages. A malformed hash never hangs or crashes the decoder: it either decodes or throws one of these errors.
import { PlaceholderError } from 'hazehash'
// or from 'hazehash/encode', which re-exports it
try {
decode(value)
} catch (error) {
if (error instanceof PlaceholderError && error.code === 'InvalidLength') {
// the value is not a hash
}
}The class and its code type are exported by hazehash, hazehash/decode and hazehash/encode:
type PlaceholderErrorCode =
'InvalidInput' | 'BudgetTooSmall' | 'InvalidLength' | 'InvalidCharacter' | 'UnsupportedVersion'
class PlaceholderError extends Error {
readonly code: PlaceholderErrorCode
}name is 'PlaceholderError'. The message is the code, followed by a colon and an explanation when there is one, for example InvalidInput: expected RGBA data of length 4·width·height.
Encoder errors
InvalidInput
The input or an option is not acceptable: the pixel buffer is not 4 · width · height bytes, width or height is not an integer of at least 1, budget, analysisSize or a weight is not a finite number, a weight is negative, profile is not one of the three names, or alpha is neither 'auto' nor a boolean. The Node.js helpers also throw it when sharp is not installed.
BudgetTooSmall
The budget is smaller than the header of the hash: 7 bytes, or 9 when the image has transparency. It is also thrown if the result could not be fitted into the budget.
Decoder errors
InvalidLength
The string or the bytes cannot be a hash: a base64url string whose length leaves a single character in the last group, or data shorter than the header (7 bytes, or 9 when the header says the hash carries alpha) or longer than 1024 bytes.
InvalidCharacter
The string has a character outside the base64url alphabet (A–Z, a–z, 0–9, -, _). Padding with = is not part of the format and is rejected too.
UnsupportedVersion
The first two bits of the header name a version this release does not know. Only version 1 exists, and a decoder rejects the reserved values instead of guessing.
Handling a bad hash in a page
A hash that comes from a database or a CMS can be empty or damaged. Checking it before drawing keeps the page working:
function safeAverageColor(hash: string | null) {
if (!hash) return null
try {
return getAverageColor(hash)
} catch {
return null
}
}The Vue component and composable do this for you: an invalid hash leaves a flat background and prints a single warning to the console. See PlaceholderImage Component.