Skip to content

extractErrorMessage

Convert an error to a readable message.

Available since v1.0.0

import { extractErrorMessage } from '@helpers4/string';
extractErrorMessage(error: unknown, stringify: string | true): string
ParameterTypeDescription
errorunknownan error
stringifystring | truestringifies the error if no extractable message is found

string — a readable message or a stringified error if stringify is true, otherwise undefined

Returns the stringified Error, including the class prefix.

extractErrorMessage(new Error('Something went wrong'))
// => 'Error: Something went wrong'

Returns the string directly when the error is a plain string.

extractErrorMessage('plain error')
// => 'plain error'

When stringify is true, falls back to JSON.stringify for unrecognized errors.

extractErrorMessage(42, true)
// => '42'

View source on GitHub