Exercise 5: Normalize API Error Message

Problem Statement

Create a function `getErrorMessage(err)` that returns string message. - if err is Error → err.message - if string → itself - else → "Something went wrong"

Sample Output:

getErrorMessage(new Error("Network error")) => "Network error"
getErrorMessage("Invalid input") => "Invalid input"
getErrorMessage({code: 500}) => "Something went wrong"

Solution

const getErrorMessage = (err) => {
  if (err instanceof Error) return err.message;
  if (typeof err === 'string') return err;
  return 'Something went wrong';
};

Explanation

Overall Goal:

  • Different types ke errors ko normalize karna.
  • User-friendly error messages return karna.

Line 1: Function header

  • const getErrorMessage = (err) => {
  • err → koi bhi error type (Error object, string, etc.).

Line 2: Error instance check

  • if (err instanceof Error) return err.message;
  • instanceof Error → kya ye Error object hai?
  • Agar hai → err.message return (Error ka message property).
  • Example: new Error("Failed")"Failed".

Line 3: String check

  • if (typeof err === 'string') return err;
  • typeof err === 'string' → kya ye string hai?
  • Agar hai → wahi return (already message format me).

Line 4: Fallback

  • return 'Something went wrong';
  • Agar koi bhi condition match nahi hui → generic message.
  • Unknown error types handle karta hai.

Example:

  • getErrorMessage(new Error("Network error"))"Network error".
  • getErrorMessage("Invalid input")"Invalid input".
  • getErrorMessage({code: 500})"Something went wrong".

Real world:

  • Toast notifications: user-friendly error messages.
  • Error logging: consistent error format.
  • API error handling: different error types normalize.