0

What's the best practice for returning error messages to a client from a server-side script that is accessing a database?

For example, say the client sends from data using an AJAX POST and expects the server to return some JSON data to display. What if the PHP server script fails to connect to the database (I'm using mysqli_connect() )? Must I send back explicit JSON data with an error message? Or can I make use of the status object in the client-side POST callback function?

3
  • No set way of doing it, you can choose to go whatever route you want. Commented Jul 2, 2013 at 14:50
  • both i guess, but client and server should understand each other, how about some error- or status-codes Commented Jul 2, 2013 at 14:57
  • Typically "best practice" is subjective and should not be asked, but the HTTP spec provides a pretty official answer for at least half of your question. Commented Jul 2, 2013 at 15:07

2 Answers 2

1

The HTTP spec actually provides error code 503 Service Unavailable which I believe applies in this situation:

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

This status code alone should be enough for the client to know there is an error (anything 4xx or 5xx is an error), but your application will have to determine what content should be sent. If the client is expecting JSON (see the Accept header) then it makes sense to send them JSON content. However, the HTTP status code is the programatic way to determine if there was a problem.

Sign up to request clarification or add additional context in comments.

Comments

0

Widely depends on the nature of the application and the clients types.

For example, if it is an internal web application, is useful to send back the error code, the error message, the file that caused the error, maybe even a full stack trace.

If it is a public website used by random clients, should be sufficient to send back a non revealing error message, ie : "An error occurred, please try again in few minutes"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.