Day 9 - Laravel 8.0的Error Handling

不管是预期或非预期,程序往往会发生一些错误,我们不希望使用者Call API或浏览网页的时候发生错误直接跳出像下面一样的错误讯息

如果太过详细的错误讯息可能会造成资安的危机,所以我们需要先把.envAPP_DEBUG的值改为False,如此一来我们看到的错误讯息会变成这样

接下来我们需要把这些错误讯息做处理,修改app\Exceptions\Handler

  • use Laravel本身就拥有的Exception
  • $this->renderable()内部撰写闭包传入Exception和Request
  • 写一个新的handleException function专门做Response的处理,当中会从传入的exception判断是属於哪种错误,判断完後传回自订的Response message
<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function(Exception $e, $request) {
            return $this->handleException($request, $e);
        });
    }

    /**
     * Handle response from exception.
     *
     * @param Request $request
     * @param \Exception $exception
     * @return JsonResponse|null
     */
    private function handleException($request, Exception $exception)
    {
        switch (true) {
            case $exception instanceof NotFoundHttpException:
                return response()->json([
                    'message' => 'Http not found.'
                ], 404);
            case $exception instanceof MethodNotAllowedHttpException:
                return response()->json([
                    'message' => 'Method not allowed.'
                ], 405);
            case $exception instanceof UnauthorizedHttpException:
                return response()->json([
                    'message' => 'Unauthorized.'
                ], 401);
        }

        return null;
    }
}

改完後,再来试试我们的API

  1. 传入未知的route

  2. 预期的route,但是传入未定义的Method

  3. 预期的route和method,但身分验证错误


<<:  [day12]Heroku 基本使用

>>:  【程序】技术债 转生成恶役菜鸟工程师避免 Bad End 的 30 件事 - 11

安装seldon

上一篇, 我们已使用 xgboost 完成训练并且产生model档, 这个model的档名为bst_...

EP16 - 用生活化的例子解释容器,是否搞错了些什麽

容器化是应用程序级别的虚拟化, 允许单个内核上有多个独立的用户空间实体, 而这些实体称为容器。 20...

Alpine Linux Porting (一点九?)

最近睡太少身体开始亮红灯Orz 来逐步解剖一下Alpine initramfs的init scrip...

30天程序语言研究

目前我最想先学习的程序语言是python,因为我现在大三在许多课程都会优先使用这个语言,如深度学习中...

JS 22 - 探险时间!深入查询物件的所有子属性!

大家好! 如果要深入查询一个多层物件,一般都是用 Object.keys 等方法,今天就是要简化这样...