如何在Laravel中使错误可报告?

huangapple go评论73阅读模式
英文:

How to make an error reportable in Laravel?

问题

I have a problem with my api, my api connects to different external apis, it uses guzzle to make requests, I would like that every 500 status error displayed for those external apis to be reportable, so I could send an alert using sentry, I have this code:

app\Exceptions\Handler.php

public function register()
{
    $this->reportable(function (Throwable $e) {
        if (app()->bound('sentry') && config('app.env') === 'production') {
            app('sentry')->captureException($e);
        }
    });
}

In my local environment the .env file is set like this:

APP_NAME=App
APP_ENV=production
APP_KEY=base64:lkjslkdjflkjlksdfb5uk=
APP_DEBUG=true
APP_URL=http://localhost
....

I did this to make some tests to see if everything is working fine, but it is not working. I disabled the MySQL and I was able to trigger the alert, but I would like to trigger the alert for all 500 errors that those APIs return. For example, if I am making a request to an external server using guzzle and it gets this 500 status error:

{
    "message": "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://invalid url' : failed to load external entity \"https://invalid\"",
    "exception": "SoapFault",
    "file": "/path/file.php",
    "line": 100,
    "trace": [
        {

I should be able to trigger the alert, but I noticed that it is not entering this method:

$this->reportable(

What can I do?

英文:

I have a problem with my api, my api connects to different external apis, it uses guzzle to make requests, I would like that every 500 status error displayed for those external apis to be reportable, so I could send an alert using sentry, I have this code:

app\Exceptions\Handler.php

 public function register()
    {
        $this->reportable(function (Throwable $e) {
         ///dd('is reportable');

            if (app()->bound('sentry') && config('app.env') === 'production') {
                app('sentry')->captureException($e);
            }
        });
    }

In my local environment the .env file is set like this:

 APP_NAME=App
    APP_ENV=production
    APP_KEY=base64:lkjslkdjflkjlksdfb5uk=
    APP_DEBUG=true
    APP_URL=http://localhost
....

I did this to make some tests to see if everything is working fine, but it is not working.
I disable the mysql and I was able to trigger the alert, but I would like to trigger the alert for all 500 errors that those apis return. For example, if I am making a request to a external server using guzzle and it get this 500 status error:

{
	"message": "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https:\/\/invalid url' : failed to load external entity \"https:\/\/invalid\"\n",
	"exception": "SoapFault",
	"file": "/path/file.php",
	"line": 100,
	"trace": [
		{

I should be able to trigger the alert but I noticed that is not entering to this method

$this->reportable(

What can I do?

答案1

得分: 1

在Laravel中,所有异常都会经过一个文件,可以在这里找到:app/Exceptions/Handler.php。

public function register()
{
    $this->reportable(function (Throwable $e) {
       Log::info($e->getMessage());
    });
}

在storage/logs/laravel.log中将创建一个新的日志,其中包含以下消息:

[2022-08-03 08:07:56] local.INFO: Undefined variable $variableMissing

使用Honeybadger进行有用的错误记录

安装Honeybadger非常简单,所以请前往Honeybadger Laravel文档并按照逐步指南进行安装。您会注意到,您只需要安装composer依赖项并设置reportable回调即可:

public function register()
{
    $this->reportable(function (Throwable $e) {
        if (app()->bound('honeybadger')) {
            app('honeybadger')->notify($e, app('request'));
        }
    });
}

在安装了Honeybadger的composer依赖项后,运行以下命令:

php artisan honeybadger:install your-project-api-key

现在,Laravel将所有错误数据发送到Honeybadger,而不是日志文件,这样更容易和更清晰地处理。

创建自定义异常

回顾一下,我们已经展示了Laravel中的错误是什么,如何编辑默认页面以及如何连接到抛出的异常。但是,让我们进一步深入本教程,并构建一个自定义异常。

自定义异常可以用于多种目的。我发现最有用的一个是为我需要查看的应用程序区域提供上下文。对于这个简单的用例和演示目的,我们将命名我们的异常为FailedToLoadHomePage,如果由于任何原因无法渲染我们的主页视图,就会触发这个异常。

启动终端,让我们开始:

php artisan make:exception FailedToLoadHomePage

这将为我们创建一个新的类,位于app/Exceptions/FailedToLoadHomePage.php,并且此类包含以下样板:

<?php

namespace App\Exceptions;

use Exception;

class FailedToLoadHomePage extends Exception
{
    //
}

现在,我们想要返回到我们的路由文件,并在发生错误时抛出此异常:

Route::get('/', function () {
    try {
        return view('welcome', [
            'data' => $variableMissing
        ]);
    } catch (Throwable $exception) {
        throw new FailedToLoadHomePage($exception->getMessage());
    }
});

注意:上述代码中的$variableMissing是一个未定义的变量,您可能需要根据需要进行更改。

英文:

In Laravel, all exceptions pass through a file that can be found here: app/Exceptions/Handler.php.

public function register()
{
    $this-&gt;reportable(function (Throwable $e) {
       Log::info($e-&gt;getMessage());
    });
}

there will be a new log created in storage/logs/laravel.log that will contain the following message

looks like this

[2022-08-03 08:07:56] local.INFO: Undefined variable $variableMissing

Useful Error Logging with Honeybadger

Installing Honeybadger is simple and easy, so please head over to the Honeybadger Laravel Docs and follow the step-by-step guide to install it. You will notice that all you need to do is install the composer dependency and set up the reportable callback:

public function register()
{
    $this-&gt;reportable(function (Throwable $e) {
        if (app()-&gt;bound(&#39;honeybadger&#39;)) {
            app(&#39;honeybadger&#39;)-&gt;notify($e, app(&#39;request&#39;));
        }
    });
}

After installing the Honeybadger composer dependency, run the following:

php artisan honeybadger:install your-project-api-key

Laravel will now send all error data to Honeybadger instead of a log file, which is much easier and cleaner to work with.

Creating Custom Exceptions

To Recap, we have shown what is considered an error in Laravel, how to edit the default pages, and how to hook into the exceptions that are thrown. However, let's take this tutorial a step further and build a custom exception.

Custom exceptions can be used for a number of purposes. The one I find most useful is to provide context for which area of the application I need to look into. For this simple use case and demo purposes, we’ll name our exception FailedToLoadHomePage and fire this if we are unable to render our home-page view for whatever reason.

Fire up that terminal and let's get started:

php artisan make: exception FailedToLoadHomePage

This will create a new class for us here app/Exceptions/FailedToLoadHomePage.php, and this class contains the following boilerplate:

&lt;?php

namespace App\Exceptions;

use Exception;

class FailedToLoadHomePage extends Exception
{
    //
}

Now what we want to do is return to our route file and throw this exception when something goes wrong.

Route::get(&#39;/&#39;, function () {
    try {
        return view(&#39;welcome&#39;, [
            &#39;data&#39; =&gt; $variableMissing
        ]);
    } catch (Throwable $exception) {
        throw new FailedToLoadHomePage($exception-&gt;getMessage());
    }
});

huangapple
  • 本文由 发表于 2023年8月5日 06:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定