如何处理Laravel 5中的异常和错误消息? [英] How to Handle Exceptions and Error Messages in Laravel 5?
问题描述
当我收到这个错误:
Connection.php中的QueryException第620行:SQLSTATE [23000]:Integrity
约束违反:1062重复输入
我可以用自己的Flash错误消息来处理它,而不是:
糟糕,看起来有些事情出错了
您有两种处理异常并显示自定义响应的方法:
1)让框架为您处理:
如果您不处理自己的例外,Laravel将在课堂上处理他们:
App \Exceptions\Handler
在 render
方法可以拦截框架上升的所有异常的渲染。
所以,如果你想在特定的异常升高的时候特别做些什么,你可以这样修改方法:
public function render($ request,Exception $ e)
{
//检查您感兴趣的异常类型
if($ e instanceof QueryException){
// do wathever you want,例如重新定位一个特定视图
return response() - > view('my.error.view',[],500 );
}
return parent :: render($ request,$ e);
}
2)自己处理例外情况: / p>
您可以使用 try-catch
块来处理异常。例如在控制器的方法中:
try
{
//将引发异常的代码
}
//捕获特定异常....
catch(QueryException $ e)
{
//...并做任何你想要的
返回response() - > view('my.error.view',[],500);
}
两种情况的主要区别是,在案例1 您正在定义一个一般应用程序范围的方法来处理特定的例外。
另一方面,在 2 ,您可以在应用程序的特定点中定义异常哈希值
When i get this error:
QueryException in Connection.php line 620: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
can i handle it with my own flash error message instead of:
Whoops, looks like something went wrong
You have two ways to handle exceptions and show a custom response:
1) Let the framework handle them for you:
If you don't handle exceptions by yourself, Laravel will handle them in the class:
App\Exceptions\Handler
In the render
method you can intercept the renderning of all the exceptions the framework rises.
So, if you want to do something in particular when a specific exception rises, you can modify that method this way:
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) Handle the exceptions by yourself:
You can handle exceptions by yourself, with try-catch
blocks. For example in a controller's method:
try
{
//code that will raise exceptions
}
//catch specific exception....
catch(QueryException $e)
{
//...and do whatever you want
return response()->view('my.error.view', [], 500);
}
The main difference between the two cases is that in case 1 you are defining a general, application-wide approach to handle specific exceptions.
On the other hand, in case 2, you can define exception hadling in specific points of your application
这篇关于如何处理Laravel 5中的异常和错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!