Error Enhancer
Analyze information from an Error
object, providing users with helpful insights and offering developers in-depth debugging assistance.
Client Components
<ErrorEnhancementBoundary>
A smart error boundary Client Component that parses an Error
object and stack trace, then generates and displays messages aimed to help users and developers.
- In development the component shows in-depth debugging help for developers.
- In production the component shows user-friendly messages.
Consumes react-error-boundary
, useErrorEnhancement
and <ErrorEnhancementFallback>
under the hood to generate and display the enhanced error messages.
Handling client errors with <ErrorEnhancementBoundary>
Live Example · TypeError
Live Example · ReferenceError
Live Example · SyntaxError
Live Example · RangeError
Live Example · URIError
'use client'
import { ErrorEnhancementBoundary } from '@trikinco/fullstack-components/client'
export default function ComponentThatMayThrow() {
return (
<ErrorEnhancementBoundary
fallback={
<p>Generating a user-friendly error message...</p>
}
>
<Button
onClick={() => {
throwsCowbellOrError()
}}
>
Howdy 🤠
</Button>
</ErrorEnhancementBoundary>
)
}
<ErrorEnhancementFallback>
A Client Component to render inside your own error boundary or a react-error-boundary
. <ErrorEnhancementFallback>
handles enhancing error messages and rendering the information.
Consumes useErrorEnhancement
under the hood to generate and display the enhanced error messages.
Live Example
'use client'
import { ErrorEnhancementFallback } from '@trikinco/fullstack-components/client'
export default function Page() {
return (
<ErrorEnhancementFallback
error={new Error('Failed to get more cowbell')}
resetErrorBoundary={() => null}
/>
)
}
Usage with react-error-boundary
The most common use for <ErrorEnhancementFallback>
is inside an error boundary, where the error to parse must be passed down for it to generate messages.
'use client'
import { ErrorBoundary } from 'react-error-boundary'
export default function SmartBoundary(props) {
const { children, ...rest } = props || {}
return (
<ErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) => (
// Handles enhancing errors and rendering UI
<ErrorEnhancementFallback
error={error}
resetErrorBoundary={resetErrorBoundary}
{...rest}
/>
)}
>
{children}
</ErrorBoundary>
)
}
useErrorEnhancement
hook
A client-side hook for parsing information from an Error
object or other source and creating helpful messages for users and developers.
See ErrorEnhancementRequestBody for available parameters.
Handling network errors with the useErrorEnhancement
hook
Live Example · HTTP `400 Bad Request`
Live Example · HTTP `401 Unauthorized`
Live Example · HTTP `403 Forbidden`
Live Example · HTTP `404 Not Found`
Live Example · HTTP `500 Internal Server Error`
Live Example · HTTP `503 Service Unavailable`
'use client'
import { useErrorEnhancement } from '@trikinco/fullstack-components/client'
export default function Page({ error }) {
const { isLoading, data } = useErrorEnhancement({
errorMessage: error?.message,
stackTrace: error?.stack,
// Optional
// Contextual info which may help with debugging.
errorContext:
'The endpoint handling /users is down for maintenance',
})
if (isLoading) {
return 'Investigating error...'
}
return (
<div role="alert">
<p className="text-2xl font-bold mb-3 mt-0 block">
{data?.title}
</p>
<p>{data?.message}</p>
<p>{data?.developmentModeContext}</p>
</div>
)
}
Setup
Add errorEnhancer: handleErrorRequest()
to the API route handler.
import {
handleFSComponents,
handleErrorRequest,
type FSCOptions,
} from '@trikinco/fullstack-components'
const fscOptions: FSCOptions = {
errorEnhancer: handleErrorRequest({
openAiApiKey: process.env.OPENAI_API_KEY || '',
appContext: 'http web app',
/**
* Overrides the output of `developmentModeContext` messages are
* shown when `process.env.NODE_ENV === 'development'`.
*
* See below for more info.
*/
isProd: true,
}),
// Additional options and handlers...
}
const fscHandler = handleFSComponents(fscOptions)
export { fscHandler as GET, fscHandler as POST }
isProd
- Omitting
isProd
,isProd: undefined
orisProd: false
shows developer debugging messages ifprocess.env.NODE_ENV === 'development'
isProd: true
shows user-friendly messages regardless ofprocess.env.NODE_ENV
API Reference
Types
ErrorParserOptions
Error enhancer API route handler options.Properties
appContexthttp web app | mobile app | desktop app
The context of the running app to analyze errors for. Helps provide the most relevant type of information.openAiApiKeystring
- default`process.env.OPENAI_API_KEY`.
isProdboolean
Overrides the output of `developmentModeContext` messages that are typically only shown when `process.env.NODE_ENV === 'development'`ErrorEnhancementRequestBodyinterface
Error enhancer request body.Properties
errorMessagestring
The error message to analyze. This will usually be `error.message` from an `Error` object.errorContextstring
Additional context and information which may help with debugging.stackTracestring
The error stack trace to analyze. This will usually be `error.stack` from an `Error` object.ErrorEnhancementResponseinterface
Error enhancer response body.Properties
messagestring
A helpful text message explaining the error to a non-technical user.titlestring
A text title related to the `message` explanation.developmentModeContextstring
A helpful text message explaining the potential cause of the error and a possible solution. The message is intended for developers. Only shown if `process.env.NODE_ENV === 'development'` and `isProd === false`ChatGptCompletionResponse
The response body for `getErrorEnhancement`.Properties
responseTextstring
The response text extracted from the completion message content.tokensUsednumber
Total number of tokens used in the request (prompt + completion).finishReasonstring
The reason the chat stopped. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.errorMessagestring
The error message if there was an error.Components
ErrorEnhancementBoundaryfunction
import { ErrorEnhancementBoundary } from '@trikinco/fullstack-components/client'
Parameters
propsErrorBoundaryPropsrequired
ErrorEnhancementFallbackPropsinterface<object>
The fallback component to show in the error boundary when an error is thrown.Properties
fallbackReactNode
React tree to show while the error enhancement is loading.errorContextstring
Additional context to pass to the error enhancement which may help with debugging.showResetBoundaryButtonboolean
Shows a button to reset the error boundary and retry the render.resetBoundaryButtonLabelReactNode
Label to display inside the reset `<button>` when `showResetBoundaryButton` is true.resetBoundaryButtonPropsHTMLAttributes<object>
Additional props to pass to the reset `<button>`.ErrorEnhancementFallbackfunction
import { ErrorEnhancementFallback } from '@trikinco/fullstack-components/client'
Parameters
propsErrorEnhancementFallbackPropsrequired
Hooks
useErrorEnhancementfunction
import { useErrorEnhancement } from '@trikinco/fullstack-components/client'
Parameters
bodyErrorEnhancementRequestBodyrequired
configUseRequestConsumerConfig<ErrorEnhancementRequestBody>
Fetch utility hook request options without the `fetcher`. Allows for overriding the default `request` config.Returns
isLoadingboolean
Fetch loading state. `true` if the fetch is in progress.isErrorboolean
Fetch error state. `true` if an error occurred.errorunknown
Fetch error object if `isError` is `true`dataErrorEnhancementResponse | undefined
Fetch response data if the fetch was successful.refetchfunction
Refetches the data.Utilities
getErrorEnhancementfunction
import { getErrorEnhancement } from '@trikinco/fullstack-components'
Parameters
requestErrorEnhancementRequestBodyrequired
optionsErrorParserOptions
fetchErrorEnhancementfunction
import { fetchErrorEnhancement } from '@trikinco/fullstack-components/client'
Parameters
bodyErrorEnhancementRequestBodyrequired
configRequestConfigOnly
Fetch utility request options without the `body`