Utilities
getErrorMessage
A function that returns a readable message for each value that code can throw.
Utilities
A function that returns a readable message for each value that code can throw.
import * as React from 'react'
import { Button, Callout, getErrorMessage } from 'ferry-ui'
// A request that fails, for the example.
function saveInvoice(): Promise<void> {
return Promise.reject(new Error('The invoice INV-2041 is already paid.'))
}
export default function GetErrorMessageHero() {
const [message, setMessage] = React.useState<string>()
const save = async () => {
setMessage(undefined)
try {
await saveInvoice()
} catch (err) {
// `err` is `unknown`: the helper gives a message that the user can read.
setMessage(getErrorMessage(err))
}
}
return (
<div className="flex w-full max-w-sm flex-col items-start gap-3">
<Button onClick={() => void save()}>Save invoice</Button>
{message && (
<Callout tone="destructive" size="sm" className="w-full">
{message}
</Callout>
)}
</div>
)
}In a catch block, the type of the error is unknown. Give the error to getErrorMessage to get a string. Then show the string in a Toast, a Callout or a Save Bar.
import { getErrorMessage, toast } from 'ferry-ui'
try {
await saveInvoice()
} catch (err) {
toast.error(getErrorMessage(err))
}ErrorState, TableErrorRow, StaleDataCallout and ConfirmDialog call this function. Do not call it again for these components.getErrorMessage is a plain function. A server component can call it.The function reads the message of an Error. It returns a string as it is. For each other value, it returns the fallback text.
| Value | Result |
|---|---|
new Error('Invoice not found') | 'Invoice not found' |
'Network error' | 'Network error' |
new Error('') | The fallback text |
'' | The fallback text |
null | The fallback text |
{ status: 503 } | The fallback text |
The second argument sets the text for a value with no message. The default is "Something went wrong."
import { Button, getErrorMessage, toast } from 'ferry-ui'
// A request that fails with a value that has no message.
function exportOrders(): Promise<void> {
return Promise.reject({ status: 503 })
}
export default function GetErrorMessageToast() {
return (
<Button
onClick={() => {
exportOrders().catch((err: unknown) => {
// The second argument replaces the default text "Something went wrong."
toast.error(getErrorMessage(err, 'Could not export the orders.'))
})
}}
>
Export orders
</Button>
)
}getErrorMessage(err, fallback) returns a string.
| Parameter | Type | Default | Role |
|---|---|---|---|
err | unknown | The value that the code threw, or the reason of a rejected promise. | |
fallback | string | 'Something went wrong.' | The text for a value with no message. |