简体   繁体   中英

ZF2 PHP Exception

I'm building an application with ZF2. I use ajax to POST some data on the application and when I trhrow a new Exception with this line:

throw new \Exception("Not Loged In.", 401);

The problem is everytime I throw a new error it returns a 500 even if I put anything as a second parameter of the exception.

Can anyone help me?

Thanks!

From zend framework's request lifecycle perspective every uncaught exception is an application error. You need a mechanism to convert that exceptions to meaningful HTTP responses before the framework convert them to an HTTP 50X for you.

For example, in your controller you can try something like below:

try {
    $this->myService->tryToDoSomethingThatNeedsAuthentication();
} catch(AuthRequiredException $e) {
    $this->getResponse()->setStatusCode($e->getCode()) // Assuming its 401
         ->setReasonPhrase($e->getMessage());
    return;
} catch(\Exception) {
    // handle other exceptions here
}

Problem is in your php configuration. Default Apache (or other server) hide details of your internal errors, so is returned short info:

Error 500 - internal server error

You must enable error_reporting:

in PHP:

http://php.net/manual/pl/function.error-reporting.php

or in php.ini in Apache configuration, and in .htaccess file it's possible. For developer's work you should show all errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM