您有两种方法来处理异常并显示自定义响应:
1)让框架为您处理它们:
如果你自己不处理异常,Laravel 会在类中处理它们:
App\Exceptions\Handler
In the render
方法您可以拦截框架引发的所有异常的呈现。
因此,如果您想在出现特定异常时执行特定操作,可以通过以下方式修改该方法:
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);
}
这两种情况的主要区别在于case 1你正在定义一个通用的、应用范围的方法来处理特定的异常。
另一方面,在case 2,您可以在中定义异常处理具体要点您的申请的