Yii2 500 internal server error

When handling a RESTful API request, if there is an error in the user request or if something unexpected happens on the server, you may simply throw an exception to notify the user that something went wrong. If you can identify the cause of the error (e.g., the requested resource does not exist), you should consider throwing an exception along with a proper HTTP status code (e.g., yiiwebNotFoundHttpException represents a 404 status code). Yii will send the response along with the corresponding HTTP status code and text. Yii will also include the serialized representation of the exception in the response body. For example:

When handling a RESTful API request, if there is an error in the user request or if something unexpected
happens on the server, you may simply throw an exception to notify the user that something went wrong.
If you can identify the cause of the error (e.g., the requested resource does not exist), you should
consider throwing an exception along with a proper HTTP status code (e.g., yiiwebNotFoundHttpException
represents a 404 status code). Yii will send the response along with the corresponding HTTP status
code and text. Yii will also include the serialized representation of the
exception in the response body. For example:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

The following list summarizes the HTTP status codes that are used by the Yii REST framework:

  • 200: OK. Everything worked as expected.
  • 201: A resource was successfully created in response to a POST request. The Location header
    contains the URL pointing to the newly created resource.
  • 204: The request was handled successfully and the response contains no body content (like a DELETE request).
  • 304: The resource was not modified. You can use the cached version.
  • 400: Bad request. This could be caused by various actions by the user, such as providing invalid JSON
    data in the request body, providing invalid action parameters, etc.
  • 401: Authentication failed.
  • 403: The authenticated user is not allowed to access the specified API endpoint.
  • 404: The requested resource does not exist.
  • 405: Method not allowed. Please check the Allow header for the allowed HTTP methods.
  • 415: Unsupported media type. The requested content type or version number is invalid.
  • 422: Data validation failed (in response to a POST request, for example). Please check the response body for detailed error messages.
  • 429: Too many requests. The request was rejected due to rate limiting.
  • 500: Internal server error. This could be caused by internal program errors.

Customizing Error Response ¶

Sometimes you may want to customize the default error response format. For example, instead of relying on
using different HTTP statuses to indicate different errors, you would like to always use 200 as HTTP status
and enclose the actual HTTP status code as part of the JSON structure in the response, like shown in the following,

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

To achieve this goal, you can respond to the beforeSend event of the response component in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the response (for both successful and failed responses) as explained when
suppress_response_code is passed as a GET parameter.

When handling a RESTful API request, if there is an error in the user request or if something unexpected
happens on the server, you may simply throw an exception to notify the user that something went wrong.
If you can identify the cause of the error (e.g., the requested resource does not exist), you should
consider throwing an exception along with a proper HTTP status code (e.g., [[yiiwebNotFoundHttpException]]
represents a 404 status code). Yii will send the response along with the corresponding HTTP status
code and text. Yii will also include the serialized representation of the
exception in the response body. For example:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

The following list summarizes the HTTP status code that are used by the Yii REST framework:

  • 200: OK. Everything worked as expected.
  • 201: A resource was successfully created in response to a POST request. The Location header
    contains the URL pointing to the newly created resource.
  • 204: The request was handled successfully and the response contains no body content (like a DELETE request).
  • 304: The resource was not modified. You can use the cached version.
  • 400: Bad request. This could be caused by various actions by the user, such as providing invalid JSON
    data in the request body, providing invalid action parameters, etc.
  • 401: Authentication failed.
  • 403: The authenticated user is not allowed to access the specified API endpoint.
  • 404: The requested resource does not exist.
  • 405: Method not allowed. Please check the Allow header for the allowed HTTP methods.
  • 415: Unsupported media type. The requested content type or version number is invalid.
  • 422: Data validation failed (in response to a POST request, for example). Please check the response body for detailed error messages.
  • 429: Too many requests. The request was rejected due to rate limiting.
  • 500: Internal server error. This could be caused by internal program errors.

Customizing Error Response

Sometimes you may want to customize the default error response format. For example, instead of relying on
using different HTTP statuses to indicate different errors, you would like to always use 200 as HTTP status
and enclose the actual HTTP status code as part of the JSON structure in the response, like shown in the following,

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

To achieve this goal, you can respond to the beforeSend event of the response component in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the response (for both successful and failed responses) as explained when
suppress_response_code is passed as a GET parameter.

За последние 24 часа нас посетили 11584 программиста и 1182 робота. Сейчас ищет 221 программист …


  1. mixnet

    С нами с:
    11 авг 2018
    Сообщения:
    146
    Симпатии:
    7

    потому что сейчас сайт на локальном сервере OpenServer, вместо .ru прописал .localhost


  2. Artur_hopf

    Artur_hopf
    Активный пользователь

    С нами с:
    7 май 2018
    Сообщения:
    2.266
    Симпатии:
    405


  3. mixnet

    С нами с:
    11 авг 2018
    Сообщения:
    146
    Симпатии:
    7


  4. lastdays

    lastdays
    Активный пользователь

    С нами с:
    27 сен 2012
    Сообщения:
    410
    Симпатии:
    73

    А тебе об этом лог не пишет?
    Файл не найден по ссылке или нет к нему доступа. Настраивай пути.


  5. mixnet

    С нами с:
    11 авг 2018
    Сообщения:
    146
    Симпатии:
    7

    так мне изначально пишет ошибка 500, как их настроить? через .htaccess? и файл .env там все прописал, в UrlManager тоже везде прописано, кстате если перехожу по ссылке вашей

    http://localhost то открывается форма ввода логина и пароля, только не видно стилей

    return [
    ‘class’ => yiiwebUrlManager::class,
    ‘enablePrettyUrl’ => true,
    ‘showScriptName’ => false,
    ];
    — Добавлено —
    у меня по такому пути нету стилей student/assets/72689a73/css/bootstrap.css?v=1575878575

    т.е yii я так понимаю генерирует ссылки и подставляет 72689a73, как сделать чтоб не генерировал?


  6. lastdays

    lastdays
    Активный пользователь

    С нами с:
    27 сен 2012
    Сообщения:
    410
    Симпатии:
    73

    Ты задал конкретный вопрос, я тебе дал конкретный ответ.

    1. Вместо этого г… «site.ru.localhost» стоило бы оставить стандартное доменное название, localhost
    2. Проверь в ручную и убедись, что файлы указанные в консоле существует. Для этого их нужно открыть в браузере и по указанному пути найти в папках на компьютере.

    Действия элементарны.

    Как настроить ошибки — сможешь нагуглить.
    По вопросам Open сервера, я думаю уместно спрашивать на форуме разработчиков.


  7. mixnet

    С нами с:
    11 авг 2018
    Сообщения:
    146
    Симпатии:
    7

    а в httpd.conf ничего прописывать не нужно?


  8. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    А чего в логах yii2? А чего в логах сервера?
    — Добавлено —
    И какие-то урлы странные, честно говоря. Какой шаблон приложения? advanced или basic? Если advanced без мультидоменности — покажите, как избавились.

установил Yii2-starter-kit на openServer и столкнулся с ошибкой

GET http://site.ru.localhost/stude… 1575878575 net::ERR_ABORTED 500 (Internal Server Error)
login:12 GET http://site.ru.localhost/stude… 1575878575 net::ERR_ABORTED 500 (Internal Server Error)
login:14 GET http://site.ru.localhost/stude… 1575878574 net::ERR_ABORTED 500 (Internal Server Error)
login:15 GET http://site.ru.localhost/stude… 1575878575 net::ERR_ABORTED 500 (Internal Server Error)
login:16 GET http://site.ru.localhost/student/css/style.css net::ERR_ABORTED 500 (Internal Server Error)
login:845 GET http://site.ru.localhost/stude… 1575878574 net::ERR_ABORTED 500 (Internal Server Error)
8login:2 Uncaught SyntaxError: Unexpected token ‘<‘
login:855 Uncaught ReferenceError: jQuery is not defined
at login:855
(anonymous) @ login:855
favicon.ico:1 GET http://site.ru.localhost/favicon.ico 500 (Internal Server Error)

как выяснить из за чего идут ошибки? использую windows + OpenServer

ЛОГИ APACHE 2.4 PHP

[Mon Dec 09 10:36:57.261690 2019] [ssl:warn] [pid 32324:tid 120] AH01909: site.localhost:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.262690 2019] [ssl:warn] [pid 32324:tid 120] AH01909: myproject.loc:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.263690 2019] [ssl:warn] [pid 32324:tid 120] AH01909: default:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.453701 2019] [ssl:warn] [pid 32324:tid 120] AH01909: site.localhost:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.484703 2019] [ssl:warn] [pid 32324:tid 120] AH01909: myproject.loc:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.485703 2019] [ssl:warn] [pid 32324:tid 120] AH01909: default:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.507704 2019] [mpm_winnt:notice] [pid 32324:tid 120] AH00455: Apache/2.4.38 (Win64) OpenSSL/1.0.2r configured — resuming normal operations
[Mon Dec 09 10:36:57.507704 2019] [mpm_winnt:notice] [pid 32324:tid 120] AH00456: Apache Lounge VC14 Server built: Feb 28 2019 15:05:01
[Mon Dec 09 10:36:57.507704 2019] [core:notice] [pid 32324:tid 120] AH00094: Command line: ‘D:\myprogramm\ospanel\modules\http\Apache_2. 4-PHP_7.0-7.1-x64\bin\httpd.exe -d D:/myProgramm/OSPanel/modules/http/Apache_2.4-PHP_7.0-7.1-x64 -f d:\myprogramm\ospanel\modules\http\Apache_2.4-PHP_7.0-7.1-x64\conf\httpd.conf’
[Mon Dec 09 10:36:57.508704 2019] [mpm_winnt:notice] [pid 32324:tid 120] AH00418: Parent: Created child process 32516
[Mon Dec 09 10:36:57.856724 2019] [ssl:warn] [pid 32516:tid 136] AH01909: site.localhost:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.856724 2019] [ssl:warn] [pid 32516:tid 136] AH01909: myproject.loc:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:57.857724 2019] [ssl:warn] [pid 32516:tid 136] AH01909: default:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:58.032734 2019] [ssl:warn] [pid 32516:tid 136] AH01909: site.localhost:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:58.032734 2019] [ssl:warn] [pid 32516:tid 136] AH01909: myproject.loc:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:58.033734 2019] [ssl:warn] [pid 32516:tid 136] AH01909: default:443:0 server certificate does NOT include an ID which matches the server name
[Mon Dec 09 10:36:58.059736 2019] [mpm_winnt:notice] [pid 32516:tid 136] AH00354: Child: Starting 150 worker threads.

ЛОГИ ИЗ MySQL-5.7-x64_error

2019-12-09T08:36:56.996675Z 0 [Note] d:myprogrammospanelmodulesdatabaseMySQL-5.7-x64binmysqld.exe (mysqld 5.7.25) starting as process 32332 …
2019-12-09T08:36:57.003675Z 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2019-12-09T08:36:57.003675Z 0 [Note] InnoDB: Uses event mutexes
2019-12-09T08:36:57.003675Z 0 [Note] InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
2019-12-09T08:36:57.003675Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2019-12-09T08:36:57.003675Z 0 [Note] InnoDB: Number of pools: 1
2019-12-09T08:36:57.003675Z 0 [Note] InnoDB: Not using CPU crc32 instructions
2019-12-09T08:36:57.006675Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2019-12-09T08:36:57.018676Z 0 [Note] InnoDB: Completed initialization of buffer pool
2019-12-09T08:36:57.080680Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2019-12-09T08:36:57.373696Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2019-12-09T08:36:57.374697Z 0 [Note] InnoDB: Setting file ‘d:myprogrammospaneluserdataMySQL-5.7-x64ibtmp1’ size to 12 MB. Physically writing the file full; Please wait …
2019-12-09T08:36:57.541706Z 0 [Note] InnoDB: File ‘d:myprogrammospaneluserdataMySQL-5.7-x64ibtmp1’ size is now 12 MB.
2019-12-09T08:36:57.543706Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2019-12-09T08:36:57.543706Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2019-12-09T08:36:57.544706Z 0 [Note] InnoDB: 5.7.25 started; log sequence number 35382446
2019-12-09T08:36:57.544706Z 0 [Note] InnoDB: Loading buffer pool(s) from d:myprogrammospaneluserdataMySQL-5.7-x64ib_buffer_pool
2019-12-09T08:36:57.545706Z 0 [Note] Plugin ‘FEDERATED’ is disabled.
2019-12-09T08:36:57.568708Z 0 [Note] Server hostname (bind-address): ‘127.0.0.1’; port: 3307
2019-12-09T08:36:57.568708Z 0 [Note] — ‘127.0.0.1’ resolves to ‘127.0.0.1’;
2019-12-09T08:36:57.568708Z 0 [Note] Server socket created on IP: ‘127.0.0.1’.
2019-12-09T08:36:57.685714Z 0 [Note] Event Scheduler: Loaded 0 events
2019-12-09T08:36:57.685714Z 0 [Note] d:myprogrammospanelmodulesdatabaseMySQL-5.7-x64binmysqld.exe: ready for connections.
Version: ‘5.7.25’ socket: » port: 3307 MySQL Community Server (GPL)
2019-12-09T08:36:57.739717Z 0 [Note] InnoDB: Buffer pool(s) load completed at 191209 10:36:57

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Yii form error
  • Yii an internal server error occurred
  • Yield from syntax error
  • Yes of course not ошибка
  • Yellow submarine vs just error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии