Php try catch 500

Как я могу заставить php возвратить 500, столкнувшись с фатальным исключением?

PHP фатальные ошибки возвращаются в качестве кода состояния 200 для HTTP-клиента. Как я могу заставить его вернуть код состояния 500 (Внутренняя ошибка сервера)?

header("HTTP/1.1 500 Internal Server Error"); 

Это именно та проблема, с которой я вчера столкнулся, и нашел решение следующим образом:

1) прежде всего, вам нужно уловить PHP фатальные ошибки, которые являются ошибкой E_ERROR. при возникновении этой ошибки скрипт будет хранить ошибку и прекратить выполнение. вы можете получить сохраненную ошибку, вызвав функцию error_get_last ().

2) до завершения сценария всегда будет вызываться функция обратного вызова register_shutdown_function (). поэтому вам необходимо зарегистрировать обработчик ошибок с помощью этой функции, чтобы сделать то, что вы хотите, в этом случае вернуть заголовок 500 и настроенную внутреннюю страницу ошибок (необязательно).

function my_error_handler() < $last_error = error_get_last(); if ($last_error && $last_error['type']==E_ERROR) < header("HTTP/1.1 500 Internal Server Error"); echo '. ';//html for 500 page >> register_shutdown_function('my_error_handler'); 

Примечание. Если вы хотите поймать собственный тип ошибки, который начинается с E_USER *, вы можете использовать функцию set_error_handler () для регистрации обработчика ошибок и запускать ошибку с помощью функции trigger_error, однако этот обработчик ошибок не может обрабатывать тип ошибки E_ERROR. см. объяснение на php.net о обработчике ошибок

Читайте также:  Php ceil to int

Я использовал «set_exception_handler» для обработки исключений uncaught.

function handleException($ex) < error_log("Uncaught exception . get_class($ex) . " message=" . $ex->getMessage() . " line=" . $ex->getLine()); ob_end_clean(); # try to purge content sent so far header('HTTP/1.1 500 Internal Server Error'); echo 'Internal error'; > set_exception_handler('handleException'); 

Невозможно обрабатывать PHP E_ERROR каким-либо образом в соответствии с документацией PHP: http://www.php.net/manual/en/function.set-error-handler.php

Также нельзя обрабатывать «E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING и большую часть E_STRICT» в соответствии с этой ссылкой.

Вы можете предоставить обработчик для другой ошибки, предупреждения и уведомлений, включая E_USER_ERROR, но это действительно не так полезно, как кажется, поскольку эта ошибка только умышленно бросается программистом с помощью trigger_error ().

И, конечно же, вы можете поймать любое исключение (даже те, которые бросают собственные PHP-функции).

Я согласен, что это проблема. Серверы НЕ должны возвращать 200 OK, когда код приложения сбой и ожоги.

Вы можете использовать обработку ошибок php

Вам придется поймать заброшенную ошибку с помощью try / catch, а затем использовать этот блок catch для отправки заголовка () с ошибкой 500.

try < . badcode. throw new Exception('error'); >catch (Exception $e) < header("Status: 500 Server Error"); var_dump($e->getMessage()); > 

Если фатальное исключение не окружено блоками try <> catch, вы должны зарегистрировать глобальный обработчик и использовать register_shutdown_function() чтобы проверить наличие ошибки на конце скрипта.

Никогда не забудьте установить header(«HTTP/1.1 200 OK», true, 200); как последняя строка любого пути выполнения:

//first things first: header("HTTP/1.1 500 Internal Server Error", true, 500); //Application code, includes, requires, etc. [. ] //somewhere something happens //die(); throw new Exception("Uncaught exception!"); //last things last, only reached if code execution was not stopped by uncaught exception or some fatal error header("HTTP/1.1 200 OK", true, 200); 

В PHP 5.4 вы можете заменить вышеописанную функцию header гораздо лучше http_response_code(200) или http_response_code(500) .

Трудная вещь при работе с фатальными ошибками (ошибки компиляции, например отсутствующая точка с запятой) заключается в том, что сценарий не будет выполнен, поэтому он не поможет установить код состояния в этом скрипте. Однако, когда вы включаете или требуете сценарий, исполняемый скрипт будет выполнен независимо от ошибок во включенном скрипте. При этом я прихожу к этому решению:

// minimize changes to this script to keep it rock-solid http_response_code(500); // PHP >= 5.4 require_once("script-i-want-to-guard-for-errors.php"); 
// do all the processsing // don't produce any output // you might want to use output buffering http_response_code(200); // PHP >= 5.4 // here you can produce the output 

Направьте свой звонок на rock-solid-script.php, и вы готовы к работе.

Мне бы лучше было установить код состояния по умолчанию на 500 в .htaccess. Это кажется мне более элегантным, но я не могу найти способ его снять. Я попробовал флаг RewriteRule R, но это предотвращает выполнение php вообще, так что это бесполезно.

Стандартная конфигурация PHP возвращает 500 при возникновении ошибки! Просто убедитесь, что ваш display_errors = выключен. Вы можете имитировать его с помощью:

ini_set('display_errors', 0); noFunction(); 

По умолчанию директива display_errors отключена по умолчанию.

Источник

When i try to use try catch, exception i get «Server error 500»

When i try to use the exception try catch statement, I always get the Server error 500. I have the exact code as in the video. It lets me do the first part when I var dump it but after i add the exception it breaks and gives me the error. Code:

try  $db = new PDO("mysql:host=localhost;dbname=shirts4mike;port=3306", "root", "PASSWORD");  $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);  $db->exec("SET NAMES 'utf8'"); > catch (Exception $e)  echo "Could not connect to the database.";  exit; >  try  $results = $db->query("SELECT name, price FROM products");  echo "Our query ran successfully."; > catch (Exception $e)  echo "Query failed.";  exit; 

1 Answer

Kevin Kenger

Kevin Kenger
Kevin Kenger

Hey Ben, If this is your exact code, it looks like you’re missing the final closing bracket in your catch statement. As for the 500 error, that’s probably appearing because PHP errors are turned off on your server. If you have access to your php.ini file, you can go in there and add display_errors = on and that should allow you to see what errors your PHP code is throwing. If you don’t have access to that file, you can log in to your cPanel and check the error logs there. It should tell you what’s going on with your PHP code and give the reason for it not working as you’d expect.

Ben B
Ben B

I just turned the setting on and its still giving me the 500 error, I also fixed my code. EDIT: Nevermind the bracket fixed my code it just wasnt updating, thanks!

Posting to the forum is only allowed for members with active accounts.
Please sign in or sign up to post.

Источник

Why does PHP throw fatal errors and break with HTTP 500 although using try/catch blocks?

Why does PHP throw fatal errors and break with HTTP 500 although using try/catch blocks?

In my AWS logs I have entries like this:

[Wed Feb 06 10:12:22.306730 2019] [php7:error] [pid 28445] [client 172.31.10.7:55646] PHP Fatal error: Uncaught Error: Class ‘comet_cache’ not found in /var/app/current/project-website-wordpress/wp-content/mu-plugins/comet-cache-ec2-enabler.php:41

Those entries are logged when some certain HTTP 500 request happens.

After checking the code I have found the following (in Line 41 in the file mentioned):

This basically makes sense — it seems like the class is not found but the execution should simply go on if this is the case. Why does PHP stop?

You are not catching because you are tring to catch an \Exception , but what’s being thrown it’s an \Error .

Considering your error message, I would say you are using PHP >= 7 (you should specificy that, error handling has changed significantly from version 5 to version 7).

On PHP >= 7, most fatal errors are reported not by raising an error, but by throwing an Error object.

So your statement could be rewritten like:

Furthermore, both Error and Exception classes implement the Throwable interface, so you could catching that directly:

 catch (\Throwable $t) < echo "caught!\n"; echo $t->getMessage(), " at ", $t->getFile(), ":", $t->getLine(), "\n"; > 

You can see it working here.

This is in no way related to AWS, but simply a PHP thing. If you were using PHP < 7 it would still not be caught, but in that case because common errors are not thrown exceptions.

If you were using PHP5, to be able to catch an error as an exception you’d need to set-up a custom error handler. The example in the manual seems quite appropriate:

function exception_error_handler($severidad, $mensaje, $fichero, $línea) < if (!(error_reporting() & $severidad)) < // Este código de error no está incluido en error_reporting return; >throw new ErrorException($mensaje, 0, $severidad, $fichero, $línea); > set_error_handler("exception_error_handler"); 

How can I get php to return 500 upon encountering a fatal exception?, 1) first of all, you need to catch PHP fatal errors, which is error type E_ERROR. when this error occurs, script will be stored the error

How can i handle a 500 internal server error ? I need an error/ exception handling option for this on runtime.?

I have an ajax request While executing it gives an internal server error 500 in PHP. It is due to a DB error. How can I catch this error and instead of stopping the execution, I need to show an error message? I use Codeigniter framework. Thank you

You can add error callback in AJAX request like:

error: function (jqXHR, textStatus, errorThrown)

More info: https://api.jquery.com/jquery.ajax/

Do you want to trap it in PHP ?

Uncaught PHP exception causing 500 server error, They cause a 500 error with display errors turned off. – Orangepill. May 18, 2013 at 0:24 · Also it will generally write to the web servers error

How to catch 500 error in Controller using Laravel

I need to connect to an API so I write a function:

try < $res4 = $client3->post('https://api.example.co.uk/Book', [ 'headers' => [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ajhsdbjhasdbasdbasd', ], 'json' => [ 'custFirstName' => $FirstName, 'custLastName' => $Surname, 'custPhone' => $Mobile, 'custEmail' => $Email, ] ]); > catch (GuzzleHttp\Exception\ClientException $e) < $response = $e->getResponse(); $result = json_decode($response->getBody()->getContents()); $item->update(['status' => 'Problems at step3']); Mail::raw('Problem at STEP 3', function ($message) use ($serial) < $message->from('asd.asd@gmail.com', 'asd.asd@gmail.com'); $message->subject('We got a problem etc.'); $message->to('john.smith@gmail.com'); >); > 

As you can see I need to make a call to API but in the case when API is down I write catch functions.

But now when API is down and API return ‘500 Internal Error’ this function is just crashed .

My question is why catch dont handle it?

How I can handle errors — when API is down or bad request. WHy catch<> doesn’t work?

UPDATE: here is my laravel.log

[2018-10-25 14:51:04] local.ERROR: GuzzleHttp\Exception\ServerException: Server error: `POST https://api.example.co.uk/Book` resulted in a `500 Internal Server Error` response: in /home/public_html/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107 Stack trace: #0 /home/public_html/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 /home/public_html/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\(Object(GuzzleHttp\Psr7\Response)) 

The problem are namespaces here, instead of:

> catch (GuzzleHttp\Exception\ClientException $e)  
> catch (\GuzzleHttp\Exception\ClientException $e)  

Otherwise PHP assumes that class is in current namespacase, so in fact when you used GuzzleHttp\Exception\ClientException in fact you probably used App\Http\Controllers\GuzzleHttp\Exception\ClientException and such exception obviously won't be thrown by Guzzle.

The exception that is fired is a ServerException instance, and catch block tries to catch ClientException.

> catch (GuzzleHttp\Exception\ServerException $e)  

in your app/exceptions/handler.php file, update the render method like this one.

/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) < if ($exception instanceof \GuzzleHttp\Exception\ClientException) < return your_response(); >return parent::render($request, $exception); > 

How to return an HTTP 500 code on any error, no matter what, You should not use 500, that indicates an internal server error. This (and other headers) should be sent before any ouput, except if you have output buffering

Источник

Оцените статью