How to bypass Laravel Exception handling

扶醉桌前 提交于 2019-12-07 01:15:16

问题


I have a method that checks if a user has valid Session info. This is supposed to throw an Exception, Guzzle\Http\Exception\BadResponseException but when I try to catch it :

catch (Guzzle\Http\Exception\BadResponseException $e) 
{
    return false;
} 
return true

Laravel doesn't get to this code and immediately starts it's own error handling. And ideas on how to bypass Laravels own implementation and use my own Catch.

EDIT: I just found out Laravel uses the same Exception handler as Symfony, so I also added the Symfony2 tag.

EDIT 2:

I sort of fixed the issue by disabling Guzzle exceptions and checking the return header manually. It's a bit of a short cut but in this case, it does the job. Thanks for the responses!


回答1:


Actually this exception can be catched in Laravel, you just have to respect (and understand) namespacing:

If you have

namespace App;

and you do

catch (Guzzle\Http\Exception\BadResponseException $e) 

PHP understands that you are trying to

catch (\App\Guzzle\Http\Exception\BadResponseException $e) 

So, for it to work you just need a root slash:

catch (\Guzzle\Http\Exception\BadResponseException $e) 

And it will work.




回答2:


By default, the app/start/global.php file contains an error handler for all exceptions. However, you may specify more handlers if needed. Handlers are called based on the type-hint of the Exception they handle. For example, you may create a handler that only handles your BadResponseException instances, like

App::error(function(Guzzle\Http\Exception\BadResponseException $exception)
{
    // Handle the exception...
    return Response::make('Error! ' . $exception->getCode());
});

Also, make sure you have a well defined (BadResponseException) class. Read more on Laravel Documentation.




回答3:


Instead of your code

catch (Guzzle\Http\Exception\BadResponseException $e) 
{
   return false;
} 
return true

use this solution

catch (\Exception $e) 
{
   return false;
} 
return true

to catch all possible exceptions thrown by Guzzle.

If you explicitly want to catch a BadResponseException you can also prepend your exception's class namespace with '\'.

catch (\Guzzle\Http\Exception\BadResponseException $e) 
{
   return false;
} 
return true


来源:https://stackoverflow.com/questions/19360215/how-to-bypass-laravel-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!