Skip to content

Get a catch block error message with TypeScript: give a more "universal" solution #206

Closed

Description

@npirotte

Hi Kent, I went through your article about error handling, because we just faced the exact same issue :)

But we figured out that the proposed solution might not fit all cases, since many framework are throwing errors that comply to the Error api, but aren't instance of Error.

Then I would propose the following implementation as a more "universal" way of handling errors:

type ErrorWithMessage = {
  message: string;
}

function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
  return typeof error === 'object' && 'message' in error;
}

function getErrorMessage(error: unknown) {
  if (isErrorWithMessage(error)) return error.message
  return String(error)
}

This should allow program to cope with any errors thrown by all frameworks (apollo, axios, etc…)

Activity

  1. kentcdodds commented on Oct 29, 2021

    @kentcdodds
    Owner

    Thanks! I've added this to the post :)

  2. jpeyper commented on Nov 3, 2021

    @jpeyper

    My typescript may not be the best, but the type guard doesn't guarantee that the message field on the error is a string, does it?

  3. kentcdodds commented on Nov 3, 2021

    @kentcdodds
    Owner

    Hi @jpeyper! You're right. I've updated the blog post to account for that. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions