2015-12-13 83 views

回答

11

有两种方式来处理异常,并显示自定义的响应:

1)让框架处理他们为你:

如果你不处理自己的异常,Laravel将处理他们在课堂:

App\Exceptions\Handler 

render方法,你可以拦截所有的框架上升到异常的renderning。 所以,如果你想要做的事,特别是当一个特定的异常上升,你可以修改的方法是这样的:

public function render($request, Exception $e) 
{ 
    //check the type of the exception you are interested at 
    if ($e instanceof QueryException) { 

     //do wathever you want, for example returining a specific view 
     return response()->view('my.error.view', [], 500); 
    } 

    return parent::render($request, $e); 
} 

2)自行处理异常:

你可以自己处理异常,try-catch块。例如,在一个控制器的方法,包括:

try 
{ 
    //code that will raise exceptions 
} 
//catch specific exception.... 
catch(QueryException $e) 
{ 
    //...and do whatever you want 
    return response()->view('my.error.view', [], 500);  
} 

两种情况之间的主要区别在于,在壳体1要定义一般,应用程序范围内的方法来处理特定的异常。

在另一方面,在情况下2,你可以在你的应用程序的特定点定义例外hadling

+0

感谢所有 我想这两种情况下,仍然有Oooops 页我敢肯定,我错过了一些东西 –

+0

尝试在catch块中放置一个'die('catched');'语句来查看代码是否正确捕获异常。如果没有,代码是否在try块内抛出异常? – Moppo

0

这是我做工精细

如果($é的instanceof \ PDOException) {

 $dbCode = trim($e->getCode()); 
     //Codes specific to mysql errors 
     switch ($dbCode) 
     { 
      case 23000: 
       $errorMessage = 'my 2300 error message '; 
       break; 
      default: 
       $errorMessage = 'database invalid'; 
     } 


     return redirect()->back()->with('message',"$errorMessage"); 


    } 
+1

在这里,你正赶上一个'PDOException'所以也许你的代码是一个上升'PDOException',而不是一个'QueryException'你在问题中 – Moppo

+0

亲爱Moppo 我也尝试 如果($Ë的instanceof除外){ 说 //做你想要的,例如返回一个特定的视图 return response() - > view('my.error.view',[],500); } return parent :: render($ request,$ e); } 并正在Handler中工作。PHP 但尝试contlloer cactch不到风度工作为什么 –

+1

如果你想以同样的方式来捕捉到控制器,你应该做的:'抓(\ $ PDOException E)' – Moppo