DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com

How to provide meaningful error messages in your API response

Let's learn how to provide meaniful error messages through examples.

Clear and concise messages

Make sure the message is clear and easy to understand for the end user.

{
  "error": "Invalid input: Missing required parameter 'email'."
}
Enter fullscreen mode Exit fullscreen mode

Include error codes

Include error codes in the response to help developers debug the issue.

{
  "error": {
    "code": 400,
    "message": "Bad Request: Invalid input data."
  }
}
Enter fullscreen mode Exit fullscreen mode

Provide suggestion to fix the issue

Sometimes the error message is not enough to fix the issue. In that case, provide a suggestion to help the user fix the issue.

{
  "error": {
    "code": 404,
    "message": "Not Found: The requested resource does not exist. Please check the URL and try again."
  }
}
Enter fullscreen mode Exit fullscreen mode

Make sure to not leak internal errors

Do not leak internal errors to the end user. Instead, log the error and provide a generic error message.

{
  "error": {
    "code": 500,
    "message": "Internal Server Error: Something went wrong. Please try again later."
  }
}
Enter fullscreen mode Exit fullscreen mode

Localization

It is optional and only valid if your API supports multiple languages.

{
  "error": {
    "code": 401,
    "message": {
      "en": "Unauthorized: Please log in to access this resource.",
      "es": "No autorizado: Por favor, inicie sesiΓ³n para acceder a este recurso."
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps you to learn some techniques to provide meaningful error messages in your API response to help developers and users πŸš€

Top comments (1)

Collapse
 
ajitforger97 profile image
Ajit Forger

Great