php - 如何在 Laravel 5 中处理异常和错误信息?

标签 php laravel error-handling exception-handling laravel-5

当我得到这个错误时:

QueryException in Connection.php line 620: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

我可以用我自己的 flash 错误消息来处理它而不是:

Whoops, looks like something went wrong

最佳答案

您有两种方法来处理异常并显示自定义响应:

1) 让框架为您处理它们:

如果你不自己处理异常,Laravel 会在类中处理:

App\Exceptions\Handler

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 block 。例如在 Controller 的方法中:

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 中,您可以在应用程序的特定点中定义异常处理

关于php - 如何在 Laravel 5 中处理异常和错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250180/

相关文章:

Swift 负平方根

php - 使用 htaccess 在共享主机中将网站 http 重定向到 Laravel 中的 https

php - Laravel 访问关系 - 检查模型中是否存在数据

python - 在批处理模式下运行IBM Doors时要检测错误的用户名和密码

php - 扩展 attach() 方法?

mysql - 在 Laravel 中使用 eloquent 找到什么相关模型?

haskell - Control.Exception.Safe,为什么 exceptT 和 Either 的行为如此不同?

php - 无法使用自己的实现覆盖 Laravel Spark 身份验证

php - 当我不把它放在 jQuery(document).ready 中时,jquery 不工作

php - 从数据库中检索一条记录