Laravel 5 如何处理异常和错误信息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34250180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:48:53  来源:igfitidea点击:

How to Handle Exceptions and Error Messages in Laravel 5?

phplaravelerror-handlingexception-handlinglaravel-5

提问by Hussain Ali

When i get this error:

当我收到此错误时:

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

Connection.php 第 620 行中的 QueryException:SQLSTATE[23000]:违反完整性约束:1062 重复条目

can i handle it with my own flash error message instead of:

我可以用我自己的 Flash 错误消息而不是:

Whoops, looks like something went wrong

哎呀,看起来出事了

回答by Moppo

You have two ways to handle exceptions and show a custom response:

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

1) Let the framework handle them for you:

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

If you don't handle exceptions by yourself, Laravel will handle them in the class:

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

App\Exceptions\Handler

In the rendermethod 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:

在该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) Handle the exceptions by yourself:

2)自己处理异常:

You can handle exceptions by yourself, with try-catchblocks. For example in a controller's method:

您可以使用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);    
}

The main difference between the two cases is that in case 1you are defining a general, application-wide approachto handle specific exceptions.

这两种情况的主要区别在于,在情况 1 中,您定义了一种通用的、应用程序范围的方法来处理特定异常。

On the other hand, in case 2, you can define exception hadling in specific pointsof your application

另一方面,在情况 2 中,您可以在应用程序的特定点定义异常处理

回答by Hussain Ali

This is work with me fine

这对我来说很好用

if ($e 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");
}