I am learning zend framework, i have setup all requirement for it as per tutorial given for zend framework, but still i got error this error :
Internal Server Error
The server encountered an internal error or misconfiguration and was
unable to complete your request.Please contact the server administrator at admin@example.com to inform
them of the time this error occurred, and the actions you performed
just before this error.More information about this error may be available in the server error
log.
How can I resolve it?
hohner
11.4k8 gold badges48 silver badges84 bronze badges
asked Jan 19, 2013 at 16:17
1
Using Zend Application you may see more information about the errors putting those lines in application.ini
:
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
500 Errors are mostly caught exeptions. You may debug the problem looking at the variables in ErrorController.php
.
Also, the most common Apache issues:
mod_rewrite
module not enabled in Apache- required
RewriteBase /
rule in .htaccess (on shared hostings) - missing
AllowOverride All
in virtual host configuration
answered Jan 19, 2013 at 16:50
takeshintakeshin
48.2k32 gold badges118 silver badges162 bronze badges
Like the message suggests, you need to check the server error log to see what the problem actually is. If you are using Apache, it’s the Apache error log that you need to check. On Linux systems this will be at somewhere like /var/log/apache2/error.log
.
answered Jan 19, 2013 at 16:20
Tim FountainTim Fountain
33k5 gold badges40 silver badges69 bronze badges
If you’re using NGINX:
Change:
location / {
try_files $uri $uri/ /index.html;
}
To:
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}
answered Jun 18, 2014 at 20:52
John FoleyJohn Foley
4,2953 gold badges21 silver badges23 bronze badges
You don’t have mod_rewrite
loaded.
Find your httpd.conf
file and locate the line:
#LoadModule rewrite_module modules/mod_rewrite.so
Remove the #
sign from the beginning of the line to uncomment and activate it.
Next, add a new section to httpd.conf that looks like this:
<Directory "C:/wamp/www/CRUD_ZEND/public">
Options FollowSymLinks
AllowOverride All
</Directory>
The `AllowOverride` directive is important. By default, `.htaccess` files are not processed unless allowed. This line allows `.htaccess` files in that named directory.
After making those changes, restart Apache and then try loading your ZF2 page again.
try this link
Try this link, it will help you. You will get a working solution,definitely.
kguest
3,7643 gold badges29 silver badges31 bronze badges
answered May 30, 2015 at 19:13
0
You need two things:
- SSH/SFTP access
- Knowledge of where your Apache config folder is located
Log files for Apache are usually stored in /etc/httpd/logs — but it depends on your Linux setup.
answered Jan 19, 2013 at 16:36
hohnerhohner
11.4k8 gold badges48 silver badges84 bronze badges
I am learning zend framework, i have setup all requirement for it as per tutorial given for zend framework, but still i got error this error :
Internal Server Error
The server encountered an internal error or misconfiguration and was
unable to complete your request.Please contact the server administrator at admin@example.com to inform
them of the time this error occurred, and the actions you performed
just before this error.More information about this error may be available in the server error
log.
How can I resolve it?
hohner
11.4k8 gold badges48 silver badges84 bronze badges
asked Jan 19, 2013 at 16:17
1
Using Zend Application you may see more information about the errors putting those lines in application.ini
:
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
500 Errors are mostly caught exeptions. You may debug the problem looking at the variables in ErrorController.php
.
Also, the most common Apache issues:
mod_rewrite
module not enabled in Apache- required
RewriteBase /
rule in .htaccess (on shared hostings) - missing
AllowOverride All
in virtual host configuration
answered Jan 19, 2013 at 16:50
takeshintakeshin
48.2k32 gold badges118 silver badges162 bronze badges
Like the message suggests, you need to check the server error log to see what the problem actually is. If you are using Apache, it’s the Apache error log that you need to check. On Linux systems this will be at somewhere like /var/log/apache2/error.log
.
answered Jan 19, 2013 at 16:20
Tim FountainTim Fountain
33k5 gold badges40 silver badges69 bronze badges
If you’re using NGINX:
Change:
location / {
try_files $uri $uri/ /index.html;
}
To:
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}
answered Jun 18, 2014 at 20:52
John FoleyJohn Foley
4,2953 gold badges21 silver badges23 bronze badges
You don’t have mod_rewrite
loaded.
Find your httpd.conf
file and locate the line:
#LoadModule rewrite_module modules/mod_rewrite.so
Remove the #
sign from the beginning of the line to uncomment and activate it.
Next, add a new section to httpd.conf that looks like this:
<Directory "C:/wamp/www/CRUD_ZEND/public">
Options FollowSymLinks
AllowOverride All
</Directory>
The `AllowOverride` directive is important. By default, `.htaccess` files are not processed unless allowed. This line allows `.htaccess` files in that named directory.
After making those changes, restart Apache and then try loading your ZF2 page again.
try this link
Try this link, it will help you. You will get a working solution,definitely.
kguest
3,7643 gold badges29 silver badges31 bronze badges
answered May 30, 2015 at 19:13
0
You need two things:
- SSH/SFTP access
- Knowledge of where your Apache config folder is located
Log files for Apache are usually stored in /etc/httpd/logs — but it depends on your Linux setup.
answered Jan 19, 2013 at 16:36
hohnerhohner
11.4k8 gold badges48 silver badges84 bronze badges
Have you just got a Zend error 500 on your website?
Internal Server Errors mostly occur due to bad settings in website rewrite rules or PHP configuration.
Zend provides better-debugging options with the help of application.ini, ErrorController.php and so on.
At Bobcares, we often get requests to fix Zend errors, as a part of our Server Management Services.
Today, let’s analyze how our Support Engineers fix the 500 error.
500 Error in Zend Framework
Before getting deeper into the error, it’s important to have a brief introduction about the Zend Framework.
Zend is one of the popular PHP frameworks for website development. Basically, the framework is a collection of PHP based packages. Developers use these packages to develop web applications.
Usually, websites show internal server error due to bad settings in website files. This error does not provide an exact reason for the errors. So, finding the actual reason is tricky.
Here is where Zend configuration plays a crucial role. That is, a few settings in Zend config files helps in debugging.
For instance, the application.ini file allows us to turn on the error display. Thus, it shows more information about the error. Let’s get deeper into this debugging feature.
Debugging Zend error 500
Error handling is important in website managing. Zend has default error trapping feature to display and log errors.
For instance, our Support Team enables error display by changing a few parameters in application.ini.
By default, the Zend configuration file is application.ini. The basic settings for error display are:
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
These settings display the error in detail. Another important debug option is checking ErrorController.php. This file contains exceptions. By checking the variables we could easily get the reason for the error.
Additionally, we ensure that PHPinfo page of the website shows the Zend debug option turned ON too.
Fixing Internal Server Error in Zend
Usually, Internal server errors are tricky. But, our Dedicated Engineers with expertise over a decade fixes it for our customers.
1. Checking .htacess file
The most obvious reason for website error 500 is in connection with the .htaccess file. Usually, bad settings in .htaccess file cause Zend error 500.
So, our Support Engineers check the rewrite rules and correct it. We also add .env variable in .htaccess. The sample code we add is,
We make sure to add the correct RewriteBase setting that determines the location at which rule applies to. Later, we restart the webserver. In most cases, this fixes the error.
2. Enabling Apache module
Similarly, disabling mod_rewrite module in Apache webserver also shows 500 error. In this case, our Support Engineers enable the module. This module is important in URL based redirection.
So, the URL redirection errors point to the disabled mod_rewrite module.
To enable the mod_rewirte first, we locate the httpd.conf. Here we uncomment the line.
LoadModule rewrite_module modules/mod_rewrite.so
Now, we add the code to enable AllowOverride
in httpd.conf. Finally, we restart the webserver to save the changes.
[Having difficulty in fixing Zend errors? – We are available 24/7.]
Conclusion
So far, we saw the Zend error 500 and debugging features in Zend. Usually, internal server error occurs due to bad settings in the .htaccess file. Today, we also saw how our Support Engineers fix it.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
Содержание
- Zend error 500 – How we fix the Internal Server Error?
- 500 Error in Zend Framework
- Debugging Zend error 500
- Fixing Internal Server Error in Zend
- 1. Checking .htacess file
- 2. Enabling Apache module
- Conclusion
- PREVENT YOUR SERVER FROM CRASHING!
- Zend Framework, IIS and 500 errors
- Documentation Expressive
- Caution
- Features
- Error Handling
- Templated Errors
- Whoops
- Container Factories and Configuration
- ZendFramework QuickStart — Создание Проекта
- Установка Zend Framework
- Создание проекта
- The Bootstraper (Загрузчик)
- Configuration (Конфигурация)
- Контроллеры действий (Action Controllers)
- Сценарии вида (views)
- Создание Виртуального Хоста (Virtual Host)
Zend error 500 – How we fix the Internal Server Error?
by Keerthi PS | Oct 23, 2019
Have you just got a Zend error 500 on your website?
Internal Server Errors mostly occur due to bad settings in website rewrite rules or PHP configuration.
Zend provides better-debugging options with the help of application.ini, ErrorController.php and so on.
At Bobcares, we often get requests to fix Zend errors, as a part of our Server Management Services.
Today, let’s analyze how our Support Engineers fix the 500 error.
500 Error in Zend Framework
Before getting deeper into the error, it’s important to have a brief introduction about the Zend Framework.
Zend is one of the popular PHP frameworks for website development. Basically, the framework is a collection of PHP based packages. Developers use these packages to develop web applications.
Usually, websites show internal server error due to bad settings in website files. This error does not provide an exact reason for the errors. So, finding the actual reason is tricky.
Here is where Zend configuration plays a crucial role. That is, a few settings in Zend config files helps in debugging.
For instance, the application.ini file allows us to turn on the error display. Thus, it shows more information about the error. Let’s get deeper into this debugging feature.
Debugging Zend error 500
Error handling is important in website managing. Zend has default error trapping feature to display and log errors.
For instance, our Support Team enables error display by changing a few parameters in application.ini.
By default, the Zend configuration file is application.ini. The basic settings for error display are:
These settings display the error in detail. Another important debug option is checking ErrorController.php. This file contains exceptions. By checking the variables we could easily get the reason for the error.
Additionally, we ensure that PHPinfo page of the website shows the Zend debug option turned ON too.
Fixing Internal Server Error in Zend
Usually, Internal server errors are tricky. But, our Dedicated Engineers with expertise over a decade fixes it for our customers.
1. Checking .htacess file
The most obvious reason for website error 500 is in connection with the .htaccess file. Usually, bad settings in .htaccess file cause Zend error 500.
So, our Support Engineers check the rewrite rules and correct it. We also add .env variable in .htaccess. The sample code we add is,
We make sure to add the correct RewriteBase setting that determines the location at which rule applies to. Later, we restart the webserver. In most cases, this fixes the error.
2. Enabling Apache module
Similarly, disabling mod_rewrite module in Apache webserver also shows 500 error. In this case, our Support Engineers enable the module. This module is important in URL based redirection.
So, the URL redirection errors point to the disabled mod_rewrite module.
To enable the mod_rewirte first, we locate the httpd.conf. Here we uncomment the line.
Now, we add the code to enable AllowOverride in httpd.conf. Finally, we restart the webserver to save the changes.
[Having difficulty in fixing Zend errors? – We are available 24/7.]
Conclusion
So far, we saw the Zend error 500 and debugging features in Zend. Usually, internal server error occurs due to bad settings in the .htaccess file. Today, we also saw how our Support Engineers fix it.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
Источник
Zend Framework, IIS and 500 errors
Join the DZone community and get the full member experience.
one of the dangers of frameworks in general is that you forget that they do lots of handy things for you.
consider zend framework’s default error controller:
the error handler in zf will catch any exceptions and route them to the error action in the error controller. this then sets the correct http response code, logs the error and optionally displays it if a config setting is set.
obviously on our production boxes, we don’t display the exceptions, but we do on our local development machines.
iis has the concept of custom error pages that it displays when the app returns a 4xx or 5xx status code:
there is also some settings for this page:
by default this is set so that if you access the site using the localhost domain, then you’ll get the zf error page and if you access the site remotely then you’ll get the iis custom page and won’t see the error.
if, like me, you are developing with your iis in a vm and using the host os’s browser and developer tools, then you need to change the setting to «detailed»:
now you can see your exceptions and it doesn’t look like php has crashed 🙂
Published at DZone with permission of Rob Allen , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.
Источник
Documentation Expressive
Caution
The documentation you are viewing is for an older version of this component.
Switch to the latest (v3) version.
Features
In This Article
Error Handling
Expressive provides error handling out of the box, via zend-stratigility’s FinalHandler implementation. This pseudo-middleware is executed in the following conditions:
- If the middleware stack is exhausted, and no middleware has returned a response.
- If an error has been passed via $next() , but not handled by any error middleware.
The FinalHandler essentially tries to recover gracefully. In the case that no error was passed, it does the following:
- If the response passed to it differs from the response provided at initialization, it will return the response directly; the assumption is that some middleware along the way called $next() with a new response.
- If the response instances are identical, it checks to see if the body size has changed; if it has, the assumption is that a middleware at some point has written to the response body.
- At this point, it assumes no middleware was able to handle the request, and creates a 404 response, indicating «Not Found.»
In the event that an error was passed, it does the following:
- If $error is not an exception, it will use the response status if it already indicates an error (ie., >= 400 status), or will use a 500 status, and return the response directly with the reason phrase.
- If $error is an exception, it will use the exception status if it already indicates an error (ie., >= 400 status), or will use a 500 status, and return the response directly with the reason phrase. If the FinalHandler was initialized with an option indicating that it is in development mode, it writes the exception stack trace to the response body.
This workflow stays the same throughout zend-expressive. But sometimes, it’s just not enough.
Templated Errors
You’ll typically want to provide error messages in your site template. To do so, we provide ZendExpressiveTemplatedErrorHandler . This class is similar to the FinalHandler , but accepts, optionally, a ZendExpressiveTemplateTemplateRendererInterface instance, and template names to use for 404 and general error conditions. This makes it a good choice for use in production.
First, of course, you’ll need to select a templating system and ensure you have the appropriate dependencies installed; see the templating documentation for information on what we support and how to install supported systems.
Once you have selected your templating system, you can setup the templated error handler.
The above will use the templates error::404 and error::500 for 404 and general errors, respectively, rendering them using our Plates template adapter.
You can also use the TemplatedErrorHandler as a substitute for the FinalHandler , without using templated capabilities, by omitting the TemplateRendererInterface instance when instantiating it. In this case, the response message bodies will be empty, though the response status will reflect the error.
See the section titled «Container Factories and Configuration», below, for techniques on configuring the TemplatedErrorHandler as your final handler within a container-based application.
Whoops
whoops is a library for providing a more usable UI around exceptions and PHP errors. We provide integration with this library through ZendExpressWhoopsErrorHandler . This error handler derives from the TemplatedErrorHandler , and uses its features for 404 status and non-exception errors. For exceptions, however, it will return the whoops output. As such, it is a good choice for use in development.
To use it, you must first install whoops:
Then you will need to provide the error handler a whoops runtime instance, as well as a WhoopsHandlerPrettyPageHandler instance. You can also optionally provide a TemplateRendererInterface instance and template names, just as you would for a TemplatedErrorHandler .
The calls to writeToOutput(false) , allowQuit(false) , and register() must be made to guarantee whoops will interoperate well with zend-expressive.
You can add more handlers if desired.
Internally, when an exception is discovered, zend-expressive adds some data to the whoops output, primarily around the request information (URI, HTTP request method, route match attributes, etc.).
See the next section for techniques on configuring the WhoopsErrorHandler as your final handler within a container-based application.
Container Factories and Configuration
The above may feel like a bit much when creating your application. As such, we provide several factories that work with container-interop-compatible container implementations to simplify setup.
In each case, you should register the selected error handler’s factory as the service ZendExpressiveFinalHandler .
Found a mistake or want to contribute to the documentation? Edit this page on GitHub!
Источник
ZendFramework QuickStart — Создание Проекта
Данная статья не является чем то сверхестественным и подойдет скорее для тех, кто начинает изучать
Zend Framework. Так уж получилось что сам я начинал изучение с версии
1.7, но незадолго после начала познания данного инструмента меня забрали в армию, и год я программированием не занимался. Сейчас до возвращения в родные края остался месяц, а так же появилось свободное время.
В начале изучения какого либо инструмента, как я заметил по себе всегда хочется иметь его под рукой, чтобы сразу же при возможности
поковыряться а не перечитывать предварительно кучу документации.
Так у меня было с Zend Framework, когда он был еще версии 1.7
Пришлось перечиать несколько статей и пересоздать кучу каталогов,
чтобы настроить рабочий Zend Framework проект. Собственно данная статья является своего рода переводом статьи Zend Framework Quick Start | Create Your Project для версии Zend Framework 1.10.5
С некоторыми исправлениями и примечаниями.
Прочитав ее я думаю вы с легкостью создадите рабочий Zend Framework
проект и сразу же перейдете к изучению на практике.
В общем то, если все же кому то статья покажется по вкусу, возьмусь
за перевод всех статей серии Quick Start.
Установка Zend Framework
Для того, чтобы создать ваш проект, для начала вам необходимо скачать и распаковать Zend Framework.
Не буду вдаваться в подробности скачки, скажу лишь, что
он лежит где то здесь
Простейший путь, получить Zend Framework включая настроенный PHP — это установить Zend Server.
Zend Server имеет инсталляторы для таких операционных сисем, как: Mac OSX, Windows, Fedora Core, и Ubuntu.
Кроме того Zend Server так же имеет универсальный установочный пакет совместимый с большинством Linux дистрибьютивов.
После установки Zend Server’a, вы сможете найти Framework в каталоге /usr/local/zend/share/ на операционных системах MacOS X и Linux или в каталоге C:Program FilesZendZendServershareZendFramework в операционной системе Windows.
Кроме того вы можете скачать последнюю версию Zend Framework в виде архива после чего распаковать его.
Создание проекта
quickstart
|— application
| |— Bootstrap.php
| |— configs
| | `— application.ini
| |— controllers
| | |— ErrorController.php
| | `— IndexController.php
| |— models
| `— views
| |— helpers
| `— scripts
| |— error
| | `— error.phtml
| `— index
| `— index.phtml
|— library
|— public
| |— .htaccess
| `— index.php
`— tests
|— application
| `— bootstrap.php
|— library
| `— bootstrap.php
`— phpunit.xml
# Symlink:
% cd library; ln -s path/to/ZendFramework/library/Zend
# Copy:
% cd library; cp -r path/to/ZendFramework/library/Zend
Теперь когда проект создан можно перейти к разбору таких понятий как
Загрузчик (Bootstraper), Конфигурация (Configuration), Контроллеры действий (Action Controllers) и Сценарии Вида (Views).
The Bootstraper (Загрузчик)
- // application/Bootstrap.php
- class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
- <
- >
* This source code was highlighted with Source Code Highlighter .
Configuration (Конфигурация)
; application/configs/application.ini
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH «/../library»
bootstrap.path = APPLICATION_PATH «/Bootstrap.php»
bootstrap.class = «Bootstrap»
appnamespace = «Application»
resources.frontController.controllerDirectory = APPLICATION_PATH «/controllers»
resources.frontController.params.displayExceptions = 0
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
Вот несколько вещей которые необходимо знать о файле конфигурации. При использовании ini конфигурационного файла вы можете использовать константы. APPLICATION_PATH — это константа. К тому же в данном файле определено несколько секций: production, staging, testing, и development. Последние три секции наследуют настройки из секции ‘production’. Данное разбиение на категории хороший путь того, чтобы гарантировать доступность настроек на каждом этапе разработки.
Контроллеры действий (Action Controllers)
- // application/controllers/IndexController.php
- class IndexController extends Zend_Controller_Action
- <
- public function init()
- <
- /* Initialize action controller here */
- >
- public function indexAction()
- <
- // action body
- >
- >
* This source code was highlighted with Source Code Highlighter .
- // application/controllers/ErrorController.php
- class ErrorController extends Zend_Controller_Action
- <
- public function errorAction()
- <
- $errors = $ this ->_getParam( ‘error_handler’ );
- switch ($errors->type) <
- case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
- case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
- case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
- // 404 error — controller or action not found
- $ this ->getResponse()->setHttpResponseCode(404);
- $ this ->view->message = ‘Page not found’ ;
- break ;
- default :
- // application error
- $ this ->getResponse()->setHttpResponseCode(500);
- $ this ->view->message = ‘Application error’ ;
- break ;
- >
- $ this ->view->exception = $errors->exception;
- $ this ->view->request = $errors->request;
- >
- >
* This source code was highlighted with Source Code Highlighter .
Необходимо отметить, что IndexController не имеет фактически ни какого кода, в то время как ErrorController ссылается на представление вида «view».
Сценарии вида (views)
- style >
- a:link,
- a:visited
- <
- color: #0398CA;
- >
- span#zf-name
- <
- color: #91BE3F;
- >
- div#welcome
- <
- color: #FFFFFF;
- background-image: url(http://framework.zend.com/images/bkg_header.jpg);
- width: 600px;
- height: 400px;
- border: 2px solid #444444;
- overflow: hidden;
- text-align: center;
- >
- div#more-information
- <
- background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif);
- height: 100%;
- >
- style >
- div id =»welcome» >
- h1 > Welcome to the span id =»zf-name» > Zend Framework! span > h1/>
- h3 > This is your project’s main page h3/>
- div id =»more-information» >
- p >
- img src =»http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png»/>
- p >
- p >
- Helpful Links: br/>
- a href =»http://framework.zend.com/» > Zend Framework Website a > |
- a href =»http://framework.zend.com/manual/en/» > Zend Framework
- Manual a >
- p >
- div >
- div >
* This source code was highlighted with Source Code Highlighter .
А так выглядит сценарий вида для контроллера ошибок (Error Controller)
Заметим что в нем присутствуют некоторые PHP инструкции.
- DOCTYPE html PUBLIC «-//W3C//DTD XHTML 1.0 Strict//EN» ;
- » http: // www . w3 . org / TR / xhtml1 / DTD / xhtml1-strict . dtd >
- html xmlns =»http://www.w3.org/1999/xhtml» >
- head >
- meta http-equiv =»Content-Type» content =»text/html; charset=utf-8″/>
- title > Zend Framework Default Application title >
- head >
- body >
- h1 > An error occurred h1 >
- h2 > php echo $ this- > message ? > h2 >
- php if ( ‘development’ == $ this- > env): ? >
- h3 > Exception information: h3 >
- p >
- b > Message: b > php echo $ this- > exception- > getMessage() ? >
- p >
- h3 > Stack trace: h3 >
- pre > php echo $ this- > exception- > getTraceAsString() ? >
- pre >
- h3 > Request Parameters: h3 >
- pre > php echo var_export ($ this- > request- > getParams(), 1) ? >
- pre >
- php endif ? >
- body >
- html >
* This source code was highlighted with Source Code Highlighter .
Создание Виртуального Хоста (Virtual Host)
В данном примере будем использовать сервер Apache. Zend Framework отлично работает и с другими серверами такими как Microsoft IIS, lighthttpd, nginx и т.д, однако большинство разработчиков должны как минимум быть знакомы с Apache.
Источник
This library addresses RFC 7807: Problem Details for HTTP APIs
for usage with PSR-7 HTTP Messages and
PSR-15 HTTP Handlers.
Problem Details for HTTP APIs
When developing APIs, it is good practice to:
- Use HTTP status codes to help convey error status.
- Provide sufficient error detail to clients.
Unfortunately, unless you are using a documented
RPC format such as
XML-RPC, JSON-RPC, or SOAP, how to return error details is not dictated, and
many API developers end up creating their own formats. Most standardized
RPC formats do not use the HTTP status code to convey an error, only the
payload, and, in fact, most clients of such services will fail if a non-200
status is returned.
RFC 7807 provides a standard format for returning problem details from HTTP
APIs. In particular, it specifies the following:
- Error responses MUST use standard HTTP status codes in the 400 or 500 range to
detail the general category of error. - Error responses will be of the
Content-Type
application/problem
,
appending a serialization format of eitherjson
orxml
:
application/problem+json
,application/problem+xml
. - Error responses will have each of the following keys:
detail
, a human-readable description of the specific error.type
, a unique URI for the general error type, generally pointing to
human-readable documentation of that given type.title
, a short, human-readable title for the general error type; the title
should not change for giventype
s.status
, conveying the HTTP status code; this is so that all information
is in one place, but also to correct for changes in the status code due to
usage of proxy servers.
Optionally, an instance
key may be present, with a unique URI for the specific
error; this will often point to an error log for that specific response.
Finally, problem details are extensible. You may provide additional keys that
give the consumer more information about the error. As an example, in an API
that has rate limiting, you may want to indicate how many requests the user has
made, what the rate limit is, and when the limit resets:
{
"type": "https://example.com/problems/rate-limit-exceeded",
"title": "You have exceeded your API rate limit.",
"detail": "You have hit your rate limit of 5000 requests per hour.",
"requests_this_hour": 5025,
"rate_limit": 5000,
"rate_limit_reset": "2017-05-03T14:39-0500"
}
Custom errors
What if you have custom error types?
RFC 7807 specifically allows you to define these with the following:
- A URI to documentation of the error type.
- A human-readable title describing the error type.
- One or more HTTP status codes associated with the error type.
For your custom errors, you use the above with a problem details response; if
the problem type requires additional information, you provide it within the
payload, and document that information at the URI describing the type.
This approach allows usage of a single, general-purpose media type for returning
problem details for your HTTP API, while allowing full customization of what
types of errors you report.
ProblemDetails
This library provides custom PSR-7 responses for JSON and XML representations of
application/problem
. Additionally, it provides a factory that will introspect
the contents of a provided Accept
header in order to determine which
representation to return, defaulting to the XML representation. This factory may
then be composed in middleware in order to create and return problem details
responses.
Additionally, the library provides middleware that acts as an error and
exception handler and wrapping calls to a request handler, converting each into problem
details responses.
Join the DZone community and get the full member experience.
Join For Free
one of the dangers of frameworks in general is that you forget that they do lots of handy things for you.
consider zend framework’s default error controller:
public function erroraction() { $errors = $this->_getparam('error_handler'); switch ($errors->type) { case zend_controller_plugin_errorhandler::exception_no_route: case zend_controller_plugin_errorhandler::exception_no_controller: case zend_controller_plugin_errorhandler::exception_no_action: // 404 error -- controller or action not found $this->getresponse()->sethttpresponsecode(404); $this->view->message = 'page not found'; break; default: // application error $this->getresponse()->sethttpresponsecode(500); $this->view->message = 'application error'; break; } // log exception, if logger available if ($log = $this->getlog()) { $log->crit($this->view->message, $errors->exception); } // conditionally display exceptions if ($this->getinvokearg('displayexceptions') == true) { $this->view->exception = $errors->exception; } $this->view->request = $errors->request; }
the error handler in zf will catch any exceptions and route them to
the error action in the error controller. this then sets the correct
http response code, logs the error and optionally displays it if a
config setting is set.
obviously on our production boxes, we don’t display the exceptions, but we do on our local development machines.
iis has the concept of custom error pages that it displays when the app returns a 4xx or 5xx status code:
there is also some settings for this page:
by default this is set so that if you access the site using the
localhost
domain, then you’ll get the zf error page and if you access the site
remotely then you’ll get the iis custom page and won’t see the error.
if, like me, you are developing with your iis in a vm and using the
host os’s browser and developer tools, then you need to change the
setting to «detailed»:
now you can see your exceptions and it doesn’t look like php has crashed
Framework
Всем привет!
Я написал форму используя zend framework
class Application_Form_User extends Zend_Form{
function __construct() {
$this->setName('form_user');
parent::__construct();
$username=new Zend_Form_Element_Text('username');
$username->setLabel('Имя');
$password=new Zend_Form_Element_Password('password');
$password->setLabel('Пароль');
$email=new Zend_Form_Element_Text('email');
$email->setLabel('Почта')
->addValidator('EmailAddress');
$submit=new Zend_Form_Element_Submit('submit');
$submit->setLabel('Регистрация');
$this->addElements(array($username,$password,$email,$submit));
}
}
Контроллер
class UsersController extends Zend_Controller_Action{
public function indexAction(){
$this->view->title='Список пользователей';
$this->view->headTitle($this->view->title,'PREPEND');
}
public function addAction(){
$this->view->title='Добавить нового пользователя';
$this->view->headTitle($this->view->title,'PREPEND');
$form=new Application_Form_User();
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
$user=new Application_Model_Users();
$user->fill($this->getValues());
$user->save();
}
}
$this->view->form=$form;
}
}
Затем создал модель
class Application_Model_Users{
protected $_dbTable;
protected $_row;
public function __construct($id=null){
$this->_dbTable=new Application_Model_DbTable_Users();
if($id){
$this->_row=$this->_dbTable->find($id)->current();
}else{
$this->_row=$this->_dbTable->createRow();
}
}
public function fill($data){
foreach($data as $kay=>$value){
if(isset($this->_row->$key)){
$this->_row->$key=$value;
}
}
}
public function save(){
$this->_row->save();
}
public function __set($name,$val){
if(isset($this->_row->$name)){
$this->_row->$name=$val;
}
}
public function __get($name){
if(isset($this->_row->$name)){
return $this->_row->$name;
}
}
$user=new Application_Model_Users($id);
}
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract{
protected $_name = 'users';
}
Но при сабмите этой формы данные не попадают в таблицу а просто вываливается 500-ая ошибка и всё!
Как можно это исправить?
Спасибо!)
One of the dangers of frameworks in general is that you forget that they do lots of handy things for you.
Consider Zend Framework’s default error controller:
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error — controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = ‘Page not found’;
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$this->view->message = ‘Application error’;
break;
}
// Log exception, if logger available
if ($log = $this->getLog()) {
$log->crit($this->view->message, $errors->exception);
}
// conditionally display exceptions
if ($this->getInvokeArg(‘displayExceptions’) == true) {
$this->view->exception = $errors->exception;
}
$this->view->request = $errors->request;
}
The error handler in ZF will catch any exceptions and route them to the error action in the error controller. This then sets the correct HTTP response code, logs the error and optionally displays it if a config setting is set.
Obviously on our production boxes, we don’t display the exceptions, but we do on our local development machines.
IIS has the concept of custom error pages that it displays when the app returns a 4xx or 5xx status code:
There is also some settings for this page:
By default this is set so that if you access the site using the localhost domain, then you’ll get the ZF error page and if you access the site remotely then you’ll get the IIS custom page and won’t see the error.
If, like me, you are developing with your IIS in a VM and using the host OS’s browser and developer tools, then you need to change the setting to “Detailed”:
Now you can see your exceptions and it doesn’t look like PHP has crashed