Should an error 500 only be thrown by the web server, or is it acceptable for your program to throw one itself?
try {
some bad code;
}
catch (Exception) {
set_header_code(500);
set_content_type('application/json');
set_response_body(json_encode({'is_error': true, 'message': 'An unknown error occurred', 'request_id': $random_number}));
}
Is this an anti-pattern?
EDIT
In response to Robert Harvey's comments:
500 Internal Server Error -- The server encountered an unexpected condition which prevented it from fulfilling the request.
Wikipedia -- A generic error message, given when no more specific message is suitable. The general catch-all error when the server-side throws an exception.
I could use this pattern to validate a form:
if ($email_address === null || !is_valid_email($email_address)) {
throw new Exception('You must supply a valid email address');
}
The server has encountered an unexpected condition which is preventing it from fulfilling the request, namely the email field is missing or invalid.
The code can then catch this error later, converting it into a nice error 500 page with some JSON data that duplicates the error.
Why would you need both error 500 and {is_error: true}
? How about if you generate an error 500 and say {is_error: false}
? What does that mean? Why not leave it as 200 OK
with {is_error: true}
?
In JavaScript:
if (http_response_code == 500) {
// The server did not respond as expected
// Do not try to parse the response body as JSON
// because there's no guarantee it contains JSON data
// Display default error message
}
else if (http_response_code == 200) {
response = parse_response_as_json();
if (response.is_error) {
display_error_message(response.message);
}
else {
// process response
}
}